Advertisement
Oppenheimer

01 knapsack

Aug 14th, 2022
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. // 01 knapsack
  2. int solve(vector<int> value , vector<int> wt , int knapsack){
  3.     int  n = value.size();
  4.     vector<vector<int>> dp (n+1 ,vecotr<int>(knapsack+1,0));
  5.     // a represents the ath element .. b represents the knapsack present
  6.    
  7.     for(int a=1;a<=n;a++){
  8.         for(int b=1;b<=knapsack;b++){
  9.             if(wt[a-1]<=b){
  10.             dp[a][b] = max(value[a-1]+dp[a-1][b-wt[a-1]] , dp[a-1][b]); //either i choose the ath element or not
  11.             }else{
  12.             dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
  13.             }
  14.         }
  15.     }
  16.     return dp[n][knapsack];
  17.  
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement