Advertisement
l_garg

Untitled

Jun 17th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4.     int t;
  5.     cin>>t;
  6.     while(t--){
  7.         int n;
  8.         cin>>n;
  9.         int W;
  10.         cin>>W;
  11.         vector<int> A(n);
  12.         for(int i=0; i<n; i++){
  13.             cin>>A[i];
  14.         }
  15.         vector<int> wt(n);
  16.         for(int i=0; i<n; i++){
  17.             cin>>wt[i];
  18.         }
  19.        
  20.         vector<vector<int> >dp(n, vector<int>(W+1));//stores the final values(not the weights)
  21.         for(int i=0; i<n; i++){
  22.             dp[i][0]=0;//if w=0; the maximum value we can make is zero
  23.         }
  24.         //in the answer first entire first row is made zero(why?) and i=0; i<=n;
  25.         for(int i=0; i<n; i++){
  26.             for(int w=1; w<=W; w++){
  27.                 if(i==0){
  28.                     (wt[i]>w) ? dp[i][w]=0 : dp[i][w]=A[i];
  29.                 }
  30.                 else if(wt[i]>w){
  31.                     dp[i][w]=dp[i-1][w];
  32.                 }
  33.                 else if(wt[i]<=W){
  34.                     dp[i][w]=max(dp[i-1][w], A[i] + dp[i-1][w-wt[i]]);
  35.                 }
  36.             }
  37.         }
  38.         cout<<dp[n-1][W]<<endl;;
  39.     }
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement