我发现thread为背包算法提供了2个背包的伪代码。 我已经尝试用C ++实现它,但它并不像假设那样工作。这是代码:
#include <cstdio>
#define MAX_W1 501
#define MAX_W2 501
int maximum(int a, int b, int c) {
int max = a>b?a:b;
return c>max?c:max;
}
int knapsack[MAX_W1][MAX_W2] = {0};
int main() {
int n, s1, s2, gain, weight; // items, sack1, sack2, gain, cost
scanf("%d %d %d", &n, &s1, &s2);
// filing knapsack
for (int i = 0; i < n; i++) {
scanf("%d %d", &gain, &weight);
for (int w1 = s1; w1 >= weight; w1--) {
for (int w2 = s2; w2 >= weight; w2--) {
knapsack[w1][w2] = maximum(
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
);
}
}
}
int result = 0;
// searching for result
for (int i = 0; i <= s1; i++) {
for (int j = 0; j <= s2; j++) {
if (knapsack[i][j] > result) {
result = knapsack[i][j];
}
}
}
printf("%d\n", result);
return 0;
}
例如以下输入:
5 4 3
6 2
3 2
4 1
2 1
1 1
我有输出:
13
显然这是错的,因为我可以拿走所有物品(1,2到第一个袋子,休息到第二个袋子),总和是16。 如果我发现伪代码错误,我将不胜感激。
我做了一些更新,因为有些人对理解输入格式有疑问:
答案 0 :(得分:3)
以下是修改代码以使其工作: -
#include <cstdio>
#define MAX_W1 501
#define MAX_W2 501
int maximum(int a, int b, int c) {
int max = a>b?a:b;
return c>max?c:max;
}
int knapsack[MAX_W1][MAX_W2] = {0};
int main() {
int n, s1, s2, gain, weight; // items, sack1, sack2, gain, cost
scanf("%d %d %d", &n, &s1, &s2);
// filing knapsack
for (int i = 0; i < n; i++) {
scanf("%d %d", &gain, &weight);
// need to fill up all the table cannot stop if one sack is full because item might fit in other
for (int w1 = s1; w1 >= 0; w1--) {
for (int w2 = s2; w2 >= 0; w2--) {
int val1=0,val2=0;
if(weight<=w1)
val1 = knapsack[w1 - weight][w2] + gain;
if(weight<=w2)
val2 = knapsack[w1][w2 - weight] + gain;
knapsack[w1][w2] = maximum(
knapsack[w1][w2], // we have best option
val1, // put into sack one
val2 // put into sack two
);
}
}
}
// No need to search for max value it always be Knapsack[s1][s2]
printf("%d\n", knapsack[s1][s2]);
return 0;
}
答案 1 :(得分:2)
您使用的算法似乎不正确,因为它只会考虑对象恰好适合两种情况的情况。我对您的代码进行了以下更改,现在它可以正常运行:
#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
);
}
}
}