java – 选择0/1背包中的物品,其中两个物品具有相同的好处|最大
|
在0/1背包问题中,如果两个项目具有相同的值,如何选择项目.应选择体重较轻的值,如何检查该状况?我使用动态编程有以下功能.
static int[] knapsack(int maxWeight,double[] weight,double[] value,int n) {
//n = no. if items
int i,w;
double array[][] = new double[n + 1][maxWeight + 1];
for (i = 0; i <= n; i++) {
for (w = 0; w <= maxWeight; w++) {
if (i == 0 || w == 0)
array[i][w] = 0;
else if (weight[i - 1] <= w)
array[i][w] = max(value[i - 1] + array[i - 1][(w -(int) weight[i - 1])],array[i - 1][w]);
else
array[i][w] = array[i - 1][w];
if (i != 0 || w != 0)
System.out.print(array[i][w] + "t");
}
System.out.println();
}
int[] selected = new int[n + 1];
for (int j = n,wt = maxWeight; j > 0; j--) {
if (array[j][wt] != array[j - 1][wt]) {
if (array[j][wt] == array[j][wt - 1]) {
selected[j] = 0;
break;
}
selected[j] = 1;
wt = wt - (int) weight[j - 1];
}
else
selected[j] = 0;
}
/** Print finally selected items **/
System.out.println("nItems selected : ");
for (int k = 1; k < n + 1; k++)
if (selected[k] == 1)
System.out.print(k +" ");
System.out.println();
return selected;
}
对于这种情况:(i,v):( 4,45)(3,20)(5,30)(2,45),maxWeight = 5;
解决方法
如果您的意思是最大限度地减少重量值.你可以检查一下
设DP [i] [j]是可以获得的最大值! 并且W [i] [j]要使用的最小重量!! 然后, if(Current Weight > Element's Weight)
{
if(DP[i-1][j-Weight[i]]+Value[i]>DP[i-1][j]){
DP[i][j]=DP[i-1][j-Weight[i]]+Value[i];
Weight[i][j]= Weight[i-1][j-Weight[i]]+Value[i]
}
else if(DP[i-1][j-Weight[i]]+Value[i] < DP[i-1][j] ){
DP[i][j]=DP[i-1][j];
Weight[i][j]=Weight[i-1][j];
}
else{ //Note this is the tricky part elsewise the
//Above conditions are simple Knapsack conditions
DP[i][j]=DP[i-1][j]; //Both of them are equal We will get same Value . Thus we cannot maximise it in any other way!!
Weight[i][j]=minimum ( Weight[i-1][j],Weight[i-1][j-Weight[i]]+A[i]);
}
}
else
{
DP[i][j]=DP[i-1][j];
Weight[i][j]=Weight[i-1][j];
}
注意解决方案是微不足道的,除非第一个条件中的第三个条件! 我假设你知道背包0/1的问题,这就是为什么我没有解释第一和第二个条件! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
