-
Notifications
You must be signed in to change notification settings - Fork 35
/
Knapsack problem.cpp
48 lines (38 loc) · 1.17 KB
/
Knapsack problem.cpp
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
#include <iostream>
#include <vector>
using namespace std;
int knapsack(int capacity, vector<int>& weights, vector<int>& values, int n) {
vector<vector<int>> dp(n + 1, vector<int>(capacity + 1, 0));
// Fill the dp table
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= capacity; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
// The maximum value is in dp[n][capacity]
return dp[n][capacity];
}
int main() {
int capacity, n;
cout << "Enter the knapsack capacity: ";
cin >> capacity;
cout << "Enter the number of items: ";
cin >> n;
vector<int> weights(n);
vector<int> values(n);
cout << "Enter the weights of items: ";
for (int i = 0; i < n; i++) {
cin >> weights[i];
}
cout << "Enter the values of items: ";
for (int i = 0; i < n; i++) {
cin >> values[i];
}
int maxValue = knapsack(capacity, weights, values, n);
cout << "Maximum value that can be obtained: " << maxValue << endl;
return 0;
}