Beingamanforever

Cooking, 0-1 Knapsack Variation, Atcoder

Dec 9th, 2024
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-12-09 14:01:31
  4.  **/
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  8. #define NeedForSpeed                  \
  9.     ios_base::sync_with_stdio(false); \
  10.     cin.tie(NULL);                    \
  11.     cout.tie(NULL);
  12. #define int long long
  13. #define all(x) (x).begin(), (x).end()
  14. typedef vector<int> vi;
  15. typedef vector<bool> vb;
  16. typedef vector<vi> vvi;
  17. typedef vector<pair<int, int>> vpi;
  18. #define f first
  19. #define s second
  20. #define yes cout << "YES" << endl
  21. #define no cout << "NO" << endl
  22. #define endl "\n"
  23. const int mod = 1000000007;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. int n, totalsum;
  26. vi a;
  27. vvi cache;
  28. int dp(int idx, int cursum)
  29. {
  30.     if (idx == n)
  31.     {
  32.         return max(cursum, totalsum - cursum);
  33.     }
  34.     int &ans = cache[idx][cursum];
  35.     if (ans != -1)
  36.     {
  37.         return ans;
  38.     }
  39.     int include = dp(idx + 1, cursum + a[idx]);
  40.     int exclude = dp(idx + 1, cursum);
  41.     ans = min(include, exclude);
  42.     return ans;
  43. }
  44.  
  45. void solve()
  46. {
  47.     // TODO: Cooking, Atcoder, 0-1 Knapsack Variation
  48.     cin >> n;
  49.     a.resize(n);
  50.     totalsum = 0;
  51.     // kind of like divide the array into two subsets with diff being min
  52.     // dp[i][j] = min time to cook first i dishes with sum j in first subset
  53.     for (int i = 0; i < n; i++)
  54.     {
  55.         cin >> a[i];
  56.         totalsum += a[i];
  57.     }
  58.     cache.assign(n, vi(totalsum + 1, -1));
  59.     cout << dp(0, 0) << endl;
  60. }
  61.  
  62. signed main()
  63. {
  64.     NeedForSpeed;
  65.     int t = 1;
  66.     // cin >> t;
  67.     while (t--)
  68.     {
  69.         solve();
  70.     }
  71.     return 0;
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment