Advertisement
sherry_ahmos

knapsack2

Nov 30th, 2022
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4.  
  5. using namespace std;
  6.  
  7. #define ll long long
  8. #define cy cout << "YES"
  9. #define cn cout << "NO"
  10. #define nl "\n"
  11. #define fi first
  12. #define se second
  13. #define cin(v) for (int i = 0; i < n, cin >> v[i]; i++)
  14. #define cout(v) for (int i = 0; i < v.size(), cout << v[i] << " "; i++)
  15. #define all(v) v.begin(), v.end()
  16. #define sz(s) s.size()
  17.  
  18. void sherry()
  19. {
  20.     ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
  21. #ifndef ONLINE_JUDGE
  22.     freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout);
  23. #endif
  24. }
  25. constexpr int MAXW = 1e5;
  26. ll n, w;
  27. vector < ll > val ,weight;
  28. vector< vector < ll > > dp;
  29. ll knapsack(ll idx, ll v)
  30. {
  31.     if(idx == n || v <= 0 )
  32.         return v == 0 ? 0 : 1e9;
  33.     ll& ret = dp[idx][v];
  34.     if(~ret)return ret;
  35.     ret = knapsack(idx + 1, v);
  36.     ret = min(ret, weight[idx] + knapsack(idx + 1, v - val[idx]));
  37.     return ret;
  38. }
  39. void solve()
  40. {
  41.     cin >> n >> w;
  42.     val.resize(n), weight.resize(n);
  43.     dp.assign(n + 10, vector < ll > (MAXW +5 , -1));
  44.     for(int i = 0; i < n; i++)
  45.         cin >> weight[i] >> val[i];
  46.     for(ll i = MAXW ; i >=0 ;i--){
  47.         if(knapsack(0,i) <= w){
  48.             return cout << i << "\n" ,void();
  49.         }
  50.     }
  51. }
  52. int main()
  53. {
  54.     sherry();
  55.     int t = 1;
  56.     // cin >> t;
  57.     while (t--)
  58.         solve();
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement