forked from v100901/hackoctoberfest2020__
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0-1 knapsacks problem.cpp
64 lines (50 loc) · 1.11 KB
/
0-1 knapsacks problem.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Returns the maximum value that
// can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Your code here
int t[n+1][W+1],i,j;
for(i=0;i<n+1;i++)
{
for(j=0;j<W+1;j++)
{
if(i==0||j==0)
t[i][j]=0;
else if(wt[i-1]<=j)
{
t[i][j]=max(val[i-1]+t[i-1][j-wt[i-1]],t[i-1][j]);
}
else
t[i][j]=t[i-1][j];
}
}
int z=t[n][W];
return z;
}
// { Driver Code Starts.
int main()
{
//taking total testcases
int t;
cin>>t;
while(t--)
{
//reading number of elements and weight
int n, w;
cin>>n>>w;
int val[n];
int wt[n];
//inserting the values
for(int i=0;i<n;i++)
cin>>val[i];
//inserting the weights
for(int i=0;i<n;i++)
cin>>wt[i];
//calling method knapSack()
cout<<knapSack(w, wt, val, n)<<endl;
}
return 0;
} // } Driver Code Ends