Skip to content

Commit 5103790

Browse files
Merge pull request matthewsamuel95#318 from RITESHMOHAPATRA/patch-1
Create 0-1_Knapsackproblem.cpp
2 parents f780316 + 8a7721a commit 5103790

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
int knapSack(int W, int *wt, int *val, int n) {
5+
int K[n+1][W+1];
6+
for (int i = 0; i <= n; i++) {
7+
for (int j = 0; j <= W; j++) {
8+
if (i==0 || j==0)
9+
K[i][j] = 0;
10+
else if (wt[i-1] <= j)
11+
K[i][j] = max(val[i-1] + K[i-1][j-wt[i-1]], K[i-1][j]);
12+
else
13+
K[i][j] = K[i-1][j];
14+
}
15+
}
16+
return K[n][W];
17+
}
18+
19+
20+
int main() {
21+
int n;
22+
cout << "\nNumber of items\t:\t";
23+
cin >> n;
24+
int val[n] , wt[n];
25+
for ( int i = 0 ;i < n;i++) {
26+
cout << "\nEnter weight and its value for " << (i+1) << "\n";
27+
cin >> wt[i];
28+
cin >> val[i];
29+
}
30+
int w;
31+
cout << "\nEnter capacity of knapsack\t:\t";
32+
cin >> w;
33+
cout << "\nThe Result is\t:\t" << knapSack(w, wt, val, n) << endl;
34+
return 0;
35+
}

0 commit comments

Comments
 (0)