0-1背包,有1个约束! (背包中只能有偶数项目)(3d数组)

时间:2017-10-24 18:03:19

标签: java dynamic-programming knapsack-problem divide-and-conquer

我正在努力为下面的问题提出一个彻底的算法。

类似于原始(或着名的)0-1背包问题,给定容量,C和项目(v,w),其中每个项目具有值,v和权重w,我们希望获得最大可能的值之和使得背包中物品的总重量将<= C.

但我们只有一个约束:   - 我们只能携带偶数件物品进入背包。

相同的方法,同样的问题要解决,但这一次,只有偶数个项目最终最大化背包中的价值总和。

这是我用于解决答案的一般Java代码方法,忽略了约束。考虑到约束,有没有办法发展这个解决方案?

public static int max(int a, int b) {
    return (a > b) ? a : b;
}

public static int knapSackMult(int capacity, Item[] items, int len,ArrayList<Item> bestItems){

    int lookup[][] = new int[len + 1][capacity + 1]; //left column and top row all 0's 
    for (int row = 0; row <= len; row++){
        for (int col = 0; col <= capacity; col++){

            //base case 
            if (row == 0 || col == 0) {
                lookup[row][col] = 0;
            }

            //if the current value's weight is <= current column (remember columns are from 0 to capacity so they indicate current weight
            else if (items[row - 1].weight <= col) {
                //will be the max of : 1) product of current value+above and left corresponding 2) one directly above 
                lookup[row][col] = max(items[row - 1].value + lookup[row - 1][col - items[row - 1].weight], lookup[row - 1][col]);
            }
            //otherwise just take the one above
            else {
                lookup[row][col] = lookup[row - 1][col];
            }
        }
    }

    int row = len; 
    int col = capacity;
    while (row > 0) {
        //if num above in LU is different than num 
        if (lookup[row][col] != lookup[row - 1][col]) {
            //add it to our sumParts since we have a valid one
            bestItems.add(items[row - 1]);
            row--; //go up a row 
            col = col - items[row].weight; //go over current number in Array times
        } 
        //otherwise go up a row
        else {
            row--;
        }
    }

    return lookup[len][capacity];
}}

class Item {

public int weight;
public int value;

public Item(int w, int v){
    this.weight = w;
    this.value = v; 
}}

0 个答案:

没有答案