-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathD-Knapsack.cpp
More file actions
49 lines (44 loc) · 846 Bytes
/
D-Knapsack.cpp
File metadata and controls
49 lines (44 loc) · 846 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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define vi vector<int>
#define ii pair<int, int>
#define nl "\n"
const ll r = 105;
const ll c = 100005;
ll weight[r];
ll cost[r];
ll dp[r][c];
bool visited[r][c];
ll n, w;
ll knapsack(ll pos, ll w) {
if(pos == n) {
return 0;
}
if(visited[pos][w]) {
return dp[pos][w];
}
ll ans = 0;
visited[pos][w] = true;
if(w - weight[pos] >= 0) {
ans = max (ans, knapsack(pos+1, w - weight[pos]) + cost[pos]);
}
ans = max (ans, knapsack(pos+1, w));
dp[pos][w] = ans;
return ans;
}
void solve(){
cin >> n >> w;
for(int i=0; i<n; i++){
cin >> weight[i] >> cost[i];
}
cout << knapsack(0, w);
}
int main(){
ios_base::sync_with_stdio(false);cin.tie(nullptr);
int t = 1;
// cin >> t;
while(t--)
solve();
return 0;
}