I've found thread which provides pseudo-code for knapsack algorithm with 2 knapsacks. I've tried implement it in C++, but it doesn't work as suppose. Here's code:
#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;
}
For instance for following input:
5 4 3
6 2
3 2
4 1
2 1
1 1
I have output:
13
Obviously it's wrong because I can take all items (1,2 into first bag and rest to second bag) and sum is 16. I would be grateful for any explanation where I get pseudo-code wrong.
I made little update since, some people have problem with understanding the input format:
- First line contains 3 numbers as follows number of items, capacity of sack one, capacity of sack two
- Later on there are n lines where each contains 2 numbers: gain, cost of i-th item.
- Assume that sacks cannot be larger than 500.