In the backpack problem 0/1, how to select elements if two elements have the same value. You should choose a value with a lower weight, how can I check this condition? I have the following function using dynamic programming.
static int[] knapsack(int maxWeight, double[] weight, double[] value, int n) {
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;
}
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;
}
For this type of case: (i, v): (4.45) (3.20) (5.30) (2.45), maxWeight = 5; where points 1 and 4 have the same meaning, he must choose an element with a lower weight, which is equal to the 4th. how to implement this condition in the above code. Description of the problem:
- , . , , .