Advertisement
pkbagchi

0-1 Knapsack

Mar 16th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main ()
  6. {
  7.     int profit[100][100], wt[100], value[100];
  8.     int n, W;
  9.     cin >> n;
  10.     for(int i = 0; i < n; i++) cin >> value[i] >> wt[i];
  11.  
  12.     cin >> W;
  13.  
  14.     for(int i = 0; i <= n; i++) {
  15.         for(int j = 0; j <= W; j++) {
  16.             if(i == 0 || j == 0) profit[i][j] = 0;
  17.             else if(j >= wt[i-1]) {
  18.                 profit[i][j] = max(profit[i-1][j], value[i-1]+profit[i-1][j-wt[i-1]]);
  19.             }
  20.             else {
  21.                 profit[i][j] = profit[i-1][j];
  22.             }
  23.         }
  24.     }
  25.     cout << profit[n][W];
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement