您使用的算法似乎不正确,因为它只会考虑对象恰好适合两个麻袋的情况。我对您的代码进行了以下更改,并且现在可以正常运行:
#include <algorithm>using std::max;int max3(int a, int b, int c) { return max(a, max(b, c));}和
for (int w1 = s1; w1 >= 0; w1--) { for (int w2 = s2; w2 >= 0; w2--) { if (w1 >= weight && w2 >= weight) // either sack has room { knapsack[w1][w2] = max3( knapsack[w1][w2], // we have best option knapsack[w1 - weight][w2] + gain, // put into sack one knapsack[w1][w2 - weight] + gain // put into sack two ); } else if (w1 >= weight) // only sack one has room { knapsack[w1][w2] = max( knapsack[w1][w2], // we have best option knapsack[w1 - weight][w2] + gain // put into sack one ); } else if (w2 >= weight) // only sack two has room { knapsack[w1][w2] = max( knapsack[w1][w2], // we have best option knapsack[w1][w2 - weight] + gain // put into sack two ); } }}


