Advertisement
Oppenheimer

unbounded knapsack

Aug 14th, 2022
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. // unbounded knapsack // only difference from 01 is that we can choose one element multiple times.
  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][b-wt[a-1]] , dp[a-1][b]); //here we can choose ith element again
  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