Skip to content

Commit 07a8658

Browse files
authored
0/1 Knapsack problem (Dynamic Programming) in C++
1 parent 9f9ce3f commit 07a8658

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
//This is a code for 01 Knapsack problem.
2+
//input for number of items, capacity of the bag (total weight the bag can take).
3+
//Input for values of each items and their weights.
4+
//Output is maximum possible value the bag can take.
5+
#include <bits/stdc++.h>
6+
using namespace std;
7+
8+
int main() {
9+
10+
int Number_of_items, Capacity;
11+
cout<<"Enter total number of items and capacity:\n";
12+
cin>>Number_of_items>>Capacity;
13+
14+
vector<int> values (Number_of_items+1);
15+
vector<int> weights (Number_of_items+1);
16+
values[0] = 0;
17+
weights[0] = 0;
18+
19+
//DP array.
20+
vector<vector<int>> dp (Number_of_items+1, vector<int>(Capacity+1, 0));
21+
22+
//Input for values
23+
cout<<"Enter the values of each items:\n";
24+
for(int i=1; i<Number_of_items+1; i++){
25+
cin>>values[i];
26+
}
27+
28+
//Input for weights of the items with respect to values.
29+
cout<<"Enter the values of each weights:\n";
30+
for(int i=1; i<Number_of_items+1; i++){
31+
cin>>weights[i];
32+
}
33+
34+
//Main algo for 0/1 Knapsack.
35+
for(int i=1; i<Number_of_items+1; i++){
36+
int wnow = weights[i];
37+
int vnow = values[i];
38+
for(int j=1; j<Capacity+1; j++){
39+
if(j < wnow){
40+
dp[i][j] = dp[i-1][j];
41+
}
42+
else{
43+
dp[i][j] = max(dp[i-1][j], values[i] + dp[i-1][j - weights[i]]);
44+
}
45+
}
46+
}
47+
48+
cout<<"The maximum value the bag can store with the given capacity is: ";
49+
cout<<dp[Number_of_items][Capacity]<<"\n";
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)