-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack(0-1).cpp
More file actions
41 lines (37 loc) · 991 Bytes
/
Knapsack(0-1).cpp
File metadata and controls
41 lines (37 loc) · 991 Bytes
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
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll N = 1e5 + 10;
ll wt[110], val[N];
ll dp[110][N];
ll Knapsack(ll indx, ll wt_left) {
if (wt_left == 0) {
return 0;
}
if (indx < 0) {
return 0;
}
if (dp[indx][wt_left] != -1) {
return dp[indx][wt_left];
}
// function calling when wt[indx] is avoided//
ll ans = Knapsack(indx - 1, wt_left - 0);
//function calling when wt[indx] is considered//
if (wt_left - wt[indx] >= 0) {
ans = max(ans, Knapsack(indx - 1, wt_left - wt[indx]) + val[indx]);
}
return dp[indx][wt_left] = ans;
}
void solve() {
memset(dp, -1, sizeof(dp));
ll n, w;
cin >> n >> w;
for (int i = 0; i < n; i++) {
cin >> wt[i] >> val[i];
}
cout << Knapsack(n - 1, w) << endl;
}
int main() {
solve();
return 0;
}