-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKnapsack0_1.cpp
More file actions
73 lines (59 loc) · 1.63 KB
/
Copy pathKnapsack0_1.cpp
File metadata and controls
73 lines (59 loc) · 1.63 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
66
67
68
69
70
71
72
73
// #include <iostream>
// using namespace std;
// int knapSack(int W, int wt[], int val[], int n) {
// int dp[n + 1][W + 1];
// for (int i = 0; i <= n; i++) {
// for (int w = 0; w <= W; w++) {
// if (i == 0 || w == 0)
// dp[i][w] = 0;
// else 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];
// }
// }
// return dp[n][W];
// }
// int main() {
// int val[] = {60, 100, 120};
// int wt[] = {10, 20, 30};
// int W = 50;
// int n = sizeof(val)/sizeof(val[0]);
// cout << "Maximum value: " << knapSack(W, wt, val, n);
// }
// user input version
#include <iostream>
using namespace std;
int knapSack(int W, int wt[], int val[], int n)
{
int dp[n + 1][W + 1];
for (int i = 0; i <= n; i++)
{
for (int w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
dp[i][w] = 0;
else 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];
}
}
return dp[n][W];
}
int main()
{
int n, W;
cout << "Enter number of items: ";
cin >> n;
int val[n], wt[n];
cout << "Enter values of items: ";
for (int i = 0; i < n; i++)
cin >> val[i];
cout << "Enter weights of items: ";
for (int i = 0; i < n; i++)
cin >> wt[i];
cout << "Enter knapsack capacity: ";
cin >> W;
cout << "\nMaximum value that can be obtained = " << knapSack(W, wt, val, n) << endl;
}