-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
0 1 Knapsack.cpp
49 lines (43 loc) · 882 Bytes
/
0 1 Knapsack.cpp
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 <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
//code
int T;
cin>>T;
while(T--)
{
int N, W;
cin>>N>>W;
vector<int> wt(N), v(N);
vector<vector<int>> wvt(N+1, vector<int>(W+1));
int i;
//int mx = INT_MIN;
for(i=0; i<N; i++)
{
cin>>v[i];
}
for(i=0; i<N; i++)
{
cin>>wt[i];
}
int w;
for (i = 0; i <= N; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
wvt[i][w] = 0;
else if (wt[i - 1] <= w)
wvt[i][w] = max(
v[i - 1] + wvt[i - 1][w - wt[i - 1]],
wvt[i - 1][w]);
else
wvt[i][w] = wvt[i - 1][w];
}
}
cout<<wvt[N][W]<<endl;
wt.clear();
v.clear();
wvt.clear();
}
return 0;
}