京东笔试题糖果因子最大组合 哪里有问题呀

import java.util.Scanner;
import java.util.Stack;
public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			int N = in.nextInt();
			int capacity = in.nextInt();
			int[] order = new int[N];
			int[] factor = new int[N];
			for (int i = 0; i < N; i++) {
				order[i] = in.nextInt();
				factor[i] = in.nextInt();
			}
			getMax(order, factor, N, capacity);

		}
		in.close();
	}

	public static void getMax(int[] order, int[] factor, int size, int capacity) {
		int[][] pre = new int[size + 1][capacity + 1];
		int[][] dp = new int[size + 1][capacity + 1];
		int maxFactor = 0;
		Stack<Integer> stack = new Stack<>();
		for (int i = 1; i <= size; i++) {
			for (int j = 1; j <= capacity; j++) {
				if (order[i - 1] > j) {
					dp[i][j] = dp[i - 1][j];
					pre[i][j] = -1;
				} else if (dp[i - 1][j] >= dp[i - 1][j - order[i - 1]] + factor[i - 1]) {
					dp[i][j] = dp[i - 1][j];
					pre[i][j] = -1;
				} else {
					dp[i][j] = dp[i - 1][j - order[i - 1]] + factor[i - 1];
					pre[i][j] = 1;
					if (factor[i - 1] > maxFactor) {
						maxFactor = factor[i - 1];
					}
				}
			}
		}
		int capa = dp[size][capacity];
		if (dp[size][capacity] == 0) {
			System.out.println("0");
			System.out.println("No");
		} else {
			System.out.println(maxFactor);
			int i = size;
			int j = capacity;
			while (capa > 0 && i >= 1 && j >= 1) {
				if (pre[i][j] == 1) {
					stack.push(i);
					j = j - order[i - 1];
					capa -= factor[i - 1];
					i--;
				} else {
					i--;
				}
			}
		}
		while (!stack.isEmpty()) {
			System.out.print(stack.pop() + " ");
		}
		System.out.println();
		return;
	}
}

全部评论
其实排个序贪心就行了吧。。。
点赞 回复 分享
发布于 2016-04-08 22:05
这道题我的思路是 寻找和为定值的多个数,还是我理解错了?
点赞 回复 分享
发布于 2016-04-08 22:32

相关推荐

hso_:哈哈哈哈哈哈我没offer一样在同一道题开喷了
投递深圳同为数码等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务