Advertisement
Oppenheimer

rod cutting

Aug 14th, 2022
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.87 KB | None | 0 0
  1. // unbounded knapsack // only difference from 01 is that we can choose one element multiple times.
  2. // rod cutting probelm
  3. // here value array is price array and wt array is length array of rod
  4. // knapsack is total length of rod
  5. // sometimes wt array nahi di hogi to u can make one
  6. int solve(vector<int> value , vector<int> wt , int knapsack){
  7.     int  n = value.size();
  8.     vector<vector<int>> dp (n+1 ,vecotr<int>(knapsack+1,0));
  9.     // a represents the ath element .. b represents the knapsack present
  10.    
  11.     for(int a=1;a<=n;a++){
  12.         for(int b=1;b<=knapsack;b++){
  13.             if(wt[a-1]<=b){
  14.             dp[a][b] = max(value[a-1]+dp[a][b-wt[a-1]] , dp[a-1][b]); //here we can choose ith element again
  15.             }else{
  16.             dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
  17.             }
  18.         }
  19.     }
  20.     return dp[n][knapsack];
  21.  
  22. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement