Advertisement
shikhorroy

0-1 Knapsack(DP)

Aug 4th, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.57 KB | None | 0 0
  1. /********************************************
  2. *           0/1 Knapsack Code(DP).          *
  3. ********************************************/
  4. int weight[MAX];
  5. int costs[MAX], profit[MAX][MAX];
  6. int knapsack(int items, int CAP)
  7. {
  8.     for(int i = 1; i <= items; i++)
  9.     {
  10.         for(int w = 1; w <= CAP; w++)
  11.         {
  12.             if(weight[i] > w)
  13.                 profit[i][w] = profit[i-1][w];
  14.             else
  15.                 profit[i][w] = max(profit[i-1][w],
  16.                 profit[i-1][w-weight[i]] + costs[i]);
  17.         }
  18.     }
  19.     return profit[items][CAP];
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement