Advertisement
splash365

0 1 knapsack

Oct 6th, 2020
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define     read            freopen("input.txt","r",stdin)
  5. #define     write           freopen("output.txt","w",stdout)
  6.  
  7. const int MAXN = 100;
  8. int weight[MAXN];
  9. int value[MAXN];
  10. int N;
  11. int mxCapacity;
  12.  
  13. int dp[MAXN][MAXN];
  14. int item[MAXN][MAXN];
  15. int cnt = 0;
  16.  
  17. int call(int i, int capacity)
  18. {
  19.     if (i < 0 || capacity == 0) return 0;
  20.     if (dp[i][capacity] != -1)
  21.         return dp[i][capacity];
  22.     int res1 = 0, res2 = 0;
  23.     if(capacity - weight[i] >= 0) res1 = value[i] + call(i - 1, capacity - weight[i]);
  24.     res2 = call(i - 1, capacity);
  25.     if(res1 > res2)
  26.     {
  27.         item[i][capacity] = 1;
  28.     }
  29.     else
  30.         item[i][capacity] = 2;
  31.     return dp[i][capacity] = max(res1, res2);
  32. }
  33.  
  34. void printItem(int i, int capacity)
  35. {
  36.     if (item[i][capacity] == 0)
  37.         return;
  38.     if(item[i][capacity] == 1)
  39.     {
  40.         printItem(i - 1, capacity - weight[i]);
  41.         cout << weight[i] << " " << value[i] << endl;
  42.     }
  43.     else
  44.         printItem(i - 1, capacity);
  45. }
  46.  
  47.  
  48. int main()
  49. {
  50.     read;
  51.     write;
  52.     memset(dp, -1, sizeof(dp));
  53.     int mxCapacity;
  54.     cnt = 0;
  55.     cin >> N >> mxCapacity;
  56.     for (int i = 0; i < N; i++)
  57.     {
  58.         cin >> weight[i] >> value[i];
  59.     }
  60.     int ans = call(N-1, mxCapacity);
  61.     cout << "Answer: " << ans << endl;
  62.     cout << "Items Taken: " << endl;
  63.     printItem(N - 1, mxCapacity);
  64.     cout << "dp Table: " << endl;
  65.     for (int i = 0; i < N; i++)
  66.     {
  67.         for (int j = 0; j <= mxCapacity; j++)
  68.         {
  69.             cout << dp[i][j] << ' ';
  70.         }
  71.         cout << endl;
  72.     }
  73.     return 0;
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement