【发布时间】:2020-03-24 14:31:38
【问题描述】:
这个问题类似于subset-sum,我们确定一个数字列表是否有一个产生给定总和的子集,但是在这种情况下,我们被允许从列表p的元素创建一个子集,仅当它等于或大于其他列表 q 中的相应元素。同样,k 不是元素值的总和,而是可以添加的元素数。 因此,如果 k 为 3,我们需要从列表 p 中选择 3 个元素,但这些元素不能小于列表 q 的相应元素。 我是动态编程和背包新手,请帮助我。
public static List<Integer> kthPerson(int k, List<Integer> p, List<Integer> q) {
List<Integer> q1 = new ArrayList<>();
q1.addAll(q);
Collections.sort(q1);
int maxQ = q1.get(q1.size()-1);
List<Integer> res = new ArrayList<>();
int[][] dp = new int[k+1][maxQ+1];
for(int[] d:dp){
Arrays.fill(d, 0);
}
for (int u = 0; u < maxQ; u++) {
int count = 0;
for (int i = 0; i < p.size(); i++){
if (p.get(i) >= u){
dp[count][u] = i+1;
count++;
}
if (count == k){
break;
}
}
}
for (int s = 0; s < q.size(); s++) {
res.add(dp[k-1][q.get(s)]);
}
return res;
}
/*if you want to test*/
public static void main(String args[]) {
List<Integer> p = new ArrayList<>();
p.add(1);
p.add(4);
p.add(4);
p.add(3);
p.add(1);
p.add(2);
p.add(6);
List<Integer> q = new ArrayList<>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
q.add(6);
q.add(7);
kthPerson(2, p, q);
}
/*you will get
2
3
3
3
0
0
0. which is desired result but when the input is really large I get the java heap error*/
【问题讨论】:
-
你将不得不给我们更多的信息和解释,现在的问题还不清楚,如果你搜索knapsack dynamic programing java,你可以阅读你正在尝试做什么。
-
另外,由于我本能地认为“无休止的递归”是这里的根本原因,您必须提供相关源代码的所有,而不仅仅是@987654323 @函数,它本身似乎不是递归的。 SO 不是调试服务:我们需要精确 的问题,而不是“这里某个地方有错误,所以让我把它扔给你,你只需修复它。”
-
@MikeRobinson 这里没有递归我正在尝试通过在给定列表中将所有可能的值添加到最大值然后简单地在最后得到结果来进行自下而上的动态编程
-
导致错误的输入到底有多大? java最大堆大小约为2 GB(!),如果人数为250且最大的q为10,000,则可能会崩溃。您会注意到,您实际上并不需要
k+1行,只需要最后 2 行,这会有所帮助,但时间复杂度仍然很高。 -
请帮助我们帮助你@theUturn,解释一下你的输出是什么意思?给变量起有意义的名字。你还确定需要动态编程吗?
标签: java algorithm knapsack-problem