jain12

0-1 knapsack problem by DP

Jun 1st, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int KnapSack(int tot_wt,int wt[],int val[],int n){
  5.   int max_val[n+1][tot_wt+1],res=0;
  6.   for(int i=0;i<=n;i++){
  7.     for(int j=0;j<=tot_wt;j++){
  8.       if(i==0|| j==0)
  9.             max_val[i][j]=0;
  10.       else{
  11.         int x=(wt[i-1]<=j)? val[i-1]+max_val[i-1][j-wt[i-1]]:0;
  12.         max_val[i][j]=max(x,max_val[i-1][j]);
  13.         }
  14.         if(res<max_val[i][j])
  15.             res=max_val[i][j];
  16.       }
  17.     }
  18.     return res;  // or return max_val[n][tot_wt];
  19.   }
  20.  
  21. int main(){
  22.   int val[] = { 60, 100, 120 };
  23.   int wt[] = { 10, 20, 30 };
  24.   int W = 50;
  25.   int n = 3;
  26.   cout << KnapSack(W, wt, val, n);
  27.   return 0;
  28.   }
Add Comment
Please, Sign In to add comment