-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKnapsack+Solution_Reconstruction.cpp
More file actions
93 lines (66 loc) · 1.18 KB
/
Knapsack+Solution_Reconstruction.cpp
File metadata and controls
93 lines (66 loc) · 1.18 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <bits/stdc++.h>
using namespace std;
int n;
int w[3003];
int v[3003];
int W;
int dp[3003][3003];
vector<int> solution;
int rec(int i,int x){
// 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 generate(int i,int x){
if(i==n){
return;
}
int donttake = rec(i+1,x);
if(w[i] <= x){
int take = rec(i+1,x-w[i]) + v[i];
if(donttake >= take){
generate(i+1,x);
}
else{
solution.push_back(i);
generate(i+1,x-w[i]);
}
}
else{
generate(i+1,x);
}
}
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<<"Maximum value = "<<rec(0,W)<<endl;
generate(0,W);
cout<<"Items taken:"<<endl;
for(int x:solution){
cout<<x<<" ";
}
cout<<endl;
}
int main(){
solve();
}