-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzero_one knapsack.cpp
More file actions
65 lines (49 loc) · 1.41 KB
/
zero_one knapsack.cpp
File metadata and controls
65 lines (49 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int knapsack(int W, vector<int>& wt, vector<int>& val, int n, vector<int>& chosen) {
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= W; w++) {
if (wt[i - 1] <= w) {
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
int w = W;
for (int i = n; i > 0; i--) {
if (dp[i][w] != dp[i - 1][w]) {
chosen.push_back(i);
w -= wt[i - 1];
}
}
return dp[n][W];
}
int main() {
int n, W;
cout << "Enter number of items: " <<endl ;
cin >> n;
vector<int> val(n), wt(n);
cout << "Enter values of items: " << endl;
for (int i = 0; i < n; i++) {
cin >> val[i];
}
cout << "Enter weights of items: " << endl ;
for (int i = 0; i < n; i++) {
cin >> wt[i];
}
cout << "Enter maximum capacity of knapsack: " << endl ;
cin >> W;
vector<int> chosen;
int maxValue = knapsack(W, wt, val, n, chosen);
cout << "Maximum value in knapsack = " << maxValue << endl;
cout << "Items picked (1-based index): " <<endl ;
for (int i = chosen.size() - 1; i >= 0; i--) {
cout << chosen[i] << " ";
}
cout << endl;
return 0;
}