仅使用O(W)空间

时间:2017-04-07 06:20:07

标签: c++ optimization backtracking knapsack-problem

所以我编写的代码正确地找到了背包问题的最佳值。

int mat[2][size + 1];
memset(mat, 0, sizeof(mat));

int i = 0;
while(i < nItems)
{
    int j = 0;
    if(i % 2 != 0)
    {
        while(++j <= size)
        {
            if(weights[i] <= j) mat[1][j] = max(values[i] + mat[0][j - weights[i]], mat[0][j]);
            else mat[1][j] = mat[0][j];
        }
    }
    else
    {
        while(++j <= size)
        {
            if(weights[i] <= j) mat[0][j] = max(values[i] + mat[1][j - weights[i]], mat[1][j]);
            else mat[0][j] = mat[1][j];
        }
    }
    i++;
}
int val = (nItems % 2 != 0)? mat[0][size] : mat[1][size];
cout << val << endl;
return 0;

这部分我是udnerstand。但是,我试图保持相同的内存空间,即O(W),但现在也使用回溯计算最佳解决方案。这是我找麻烦的地方。我给出的提示是这个

Now suppose that we also want the optimal set of items. Recall that the goal                                                         

in finding the optimal solution in part 1 is to find the optimal path from 

entry K(0,0) to entry K(W,n). The optimal path must pass through an 

intermediate node (k,n/2) for some k; this k corresponds to the remaining 

capacity in the knapsack of the optimal solution after items n/2 + 1,...n 

have been considered

提出的问题是这个。

Implement a modified version of the algorithm from part 2 that returns not 
only the optimal value, but also the remaining capacity of the optimal 
solution after the last half of items have been considered

任何帮助都会让我开始。感谢

0 个答案:

没有答案