Advertisement
keverman

Knapsack Problem

Oct 26th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.50 KB | None | 0 0
  1. struct item
  2. {
  3.     int val, wh;
  4. };
  5.  
  6. int knapsack(int W, std::vector<item> V)
  7. {
  8.     std::vector<std::vector<int> > DP(2, std::vector<int>(W + 1, 0));
  9.  
  10.     for (int i = 1; i <= V.size(); i++)
  11.     {
  12.         for (int w = 1; w <= W; w++)
  13.             if(V[i - 1].wh <= w)
  14.                 DP[1][w] = (V[i - 1].wh <= w ? std::max(V[i - 1].val + DP[0][w - V[i - 1].wh], DP[0][w])
  15.                                              : DP[0][w]);
  16.  
  17.         std::swap(DP[0], DP[1]);
  18.     }
  19.  
  20.     return DP[0][W];
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement