-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathknapsack.cpp
More file actions
63 lines (63 loc) · 1010 Bytes
/
knapsack.cpp
File metadata and controls
63 lines (63 loc) · 1010 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
62
63
// You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that we have only one //quantity of each item.
// Example:
// Input:
// 2
// 3
// 4
// 1 2 3
// 4 5 1
// 3
// 3
// 1 2 3
// 4 5 6
// Output:
// 3
// 0
#include<iostream>
using namespace std;
int dp[1001][1001];
int kp(int w[],int v[],int wt,int n)
{
int i,j;
for(i=0;i<n+1;i++)
for(j=0;j<wt+1;j++)
{
if(i==0||j==0)
{
dp[i][j]=0;
}
for(i=1;i<n+1;i++)
for(j=1;j<wt+1;j++)
if(w[i-1]<=j)
{
dp[i][j]=max(v[i-1]+dp[i-1][j-w[i-1]],dp[i-1][j]);
}
else
{
dp[i][j]=dp[i-1][j];
}
}
return dp[n][wt];
}
int main() {
int t;
cin>>t;
while(t--)
{
int n,wt;
cin>>n;
cin>>wt;
int i,w[n],v[n];
for(i=0;i<n;i++)
{
cin>>v[i];
}
for(i=0;i<n;i++)
{
cin>>w[i];
}
int x=kp(w,v,wt,n);
cout<<x<<"\n";
}
return 0;
}