Advertisement
srijan44

01Knapsack(dp)

Feb 23rd, 2020
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int Knapsack01(int n,int s,int *wt,int *val){
  5.  
  6.     int dp[n+1][s+1];
  7.  
  8.     for(int i=0;i<=n;i++){
  9.         for(int j=0;j<=s;j++){
  10.             if(i==0 || j==0){
  11.                 dp[i][j]=0;
  12.                 continue;
  13.             }
  14.  
  15.             if(wt[i-1] <= j){
  16.                 dp[i][j] = max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]);
  17.             }
  18.             else {
  19.                 dp[i][j]=dp[i-1][j];
  20.             }
  21.         }
  22.     }
  23.  
  24.    
  25.     return dp[n][s];
  26.  
  27.  
  28. }
  29.  
  30. int main() {
  31.  
  32.     #ifndef ONLINE_JUDGE
  33.     // for getting input from input.txt
  34.     freopen("input.txt", "r", stdin);
  35.     // for writing output to output.txt
  36.     freopen("output.txt", "w", stdout);
  37.     #endif
  38.  
  39.     int n,s;
  40.     cin >> n >> s;
  41.  
  42.     int wt[n],val[n];
  43.     for(int i=0;i<n;i++) cin >> wt[i];
  44.  
  45.     for(int i=0;i<n;i++) cin >> val[i];
  46.    
  47.     cout << Knapsack01(n,s,wt,val) << endl;
  48.  
  49.     return 0;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement