-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack.cpp
More file actions
61 lines (42 loc) · 751 Bytes
/
Knapsack.cpp
File metadata and controls
61 lines (42 loc) · 751 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bits/stdc++.h>
using namespace std;
int n;
int w[3003];
int v[3003];
int W;
int dp[3003][3003];
int rec(int i, int x){
// pruning
// (not needed here)
// basecase
if(i == n){
return 0;
}
// cache check
if(dp[i][x] != -1){
return dp[i][x];
}
// transition
int ans = rec(i+1, x);
if(w[i] <= x){
ans = max(ans, rec(i+1, x - w[i]) + v[i]);
}
// save and return
dp[i][x] = ans;
return ans;
}
void solve(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> w[i];
}
for(int i = 0; i < n; i++){
cin >> v[i];
}
cin >> W;
memset(dp, -1, sizeof(dp));
cout << rec(0, W) << endl;
}
int main(){
solve();
}