如何在这个Knapsack java代码中返回权重和相应的索引?

时间:2017-07-30 23:25:16

标签: java knapsack-problem

所以我在this website关于背包0-1问题看这个代码。

我想修改他们提供的程序,以便返回选择了哪些值以及相应的索引。例如,对于这种情况,解决方案输出390但我希望打印出已选择的值。所以在这种情况下,我希望它打印出来:

Items selected :
#2 60
#3 90
#5 240

这是我到目前为止所做的:

// A Dynamic Programming based solution for 0-1 Knapsack problem
class Knapsack
{

    // A utility function that returns maximum of two integers
    static int max(int a, int b) { return (a > b)? a : b; }

// Returns the maximum value that can be put in a knapsack of capacity W
    static int knapSack(int W, int wt[], int val[], int n)
    {
        int i, w;
    int K[][] = new int[n+1][W+1];
            int[] selected = new int[n + 1];

    // Build table K[][] in bottom up manner
    for (i = 0; i <= n; i++)
    {
        for (w = 0; w <= W; w++)
        {
            if (i==0 || w==0){
                //selected[i] = 1;
                K[i][w] = 0;
            }
            else if (wt[i-1] <= w){
                selected[i] = 1;
                K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]);
            }
            else{
                selected[i]=0;
                K[i][w] = K[i-1][w];
            }
        }
    }
     System.out.println("\nItems selected : ");
        for (int x = 1; x < n + 1; x++)
            if (selected[x] == 1)
                System.out.print(x +" ");
        System.out.println();

    return K[n][W];
    }


    // Driver program to test above function
    public static void main(String args[])
    {
        int val[] = new int[]{300,60,90,100,240};
    int wt[] = new int[]{50,10,20,40,30};
    int W = 60;
    int n = val.length;
    System.out.println(knapSack(W, wt, val, n));
    }
}

我所做的是创建一个int类型的一维数组,如果选择了该值,则将索引标记为true。或者至少,这就是我想要做的事情。

但这是打印每个索引。直到我找出那部分,我才知道如何返回相应的权重。我知道我的代码中的逻辑是错误的,所以有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

不幸的是,在动态编程问题中设置哪些项目非常困难。由于解决方案必然建立在子问题解决方案的基础之上,因此您还需要存储在每个子解决方案中选择的项目,然后在最后聚合。

幸运的是,还有更好的方法。我们可以使用最终解决方案回溯,看看我们最终使用了什么值。只需用以下内容替换打印值的部分:

System.out.println("\nItems selected : ");
int tempW = W;
int y = 0; //to index in selected
for (int x = n; x > 0; x--){
    if ((tempW-wt[x-1] >= 0) && (K[x][tempW] - K[x-1][tempW-wt[x-1]] == val[x-1]) ){
        selected[y++] = x-1; //store current index and increment y
        tempW-=wt[x-1];
    }
 }
 for(int j = y-1; j >= 0; j--){
    System.out.print("#" + (selected[j]+1) + " ");
    System.out.println(val[selected[j]]);
}

这将打印:

Items selected:
#2 60
#3 90
#5 240
390

要按升序打印项目,我们必须存储它们并将它们打印在单独的for循环中。出于同样的原因,我们必须首先回溯:从起点开始有很多路径,而从结束点开始只有一条路径。