Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c4f13ea

Browse files
Zero-One Knapsack
1 parent 8981fa3 commit c4f13ea

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎knapsack.cpp‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <bits/stdc++.h>
2+
#define ll long long
3+
using namespace std;
4+
5+
int main() {
6+
ll i,j,n,w;
7+
cin>>n>>w;
8+
ll dp[n+1][w+1];
9+
ll val[n], wt[n];
10+
for(i=0;i<n;i++)
11+
cin>>val[i]>>wt[i];
12+
for(i=0;i<=n;i++) {
13+
for(j=0;j<=w;j++) {
14+
if(i==0 || j==0) {
15+
dp[i][j] = 0;
16+
}
17+
else if(j < wt[i-1]) {
18+
dp[i][j] = dp[i-1][j];
19+
}
20+
else {
21+
dp[i][j] = max(dp[i-1][j], dp[i-1][j-wt[i-1]] + val[i-1]);
22+
}
23+
}
24+
}
25+
//for(i=0;i<=n;i++) {
26+
// for(j=0;j<=w;j++)
27+
// cout<<dp[i][j]<<" ";
28+
// cout<<endl;
29+
//}
30+
cout<<dp[n][w]<<endl;
31+
return 0;
32+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /