Beingamanforever

Knapsack for All segments, Atcoder

Dec 9th, 2024 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-12-08 23:15:35
  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 = 998244353;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. const int N = 3005;
  26. int cache[N][N];
  27. int a[N];
  28. int n, s;
  29. int dp(int idx, int sum)
  30. {
  31.     if (sum == 0)
  32.     {
  33.         // since L is fixed, we have achived the sum, so possibilities for R is n-idx+2
  34.         return n - idx + 2;
  35.     }
  36.     if (idx > n)
  37.     {
  38.         return 0;
  39.     }
  40.     if (sum < 0)
  41.     {
  42.         return 0;
  43.     }
  44.     int &ans = cache[idx][sum];
  45.     if (ans != -1)
  46.     {
  47.         return ans;
  48.     }
  49.     // we have two choices, either we take the element or we don't
  50.     ans = (dp(idx + 1, sum) + dp(idx + 1, sum - a[idx])) % mod;
  51.     return ans;
  52. }
  53. void solve()
  54. {
  55.     // TODO: Knapsack for all segments
  56.     memset(cache, -1, sizeof(cache));
  57.     cin >> n >> s;
  58.     for (int i = 1; i <= n; i++)
  59.     {
  60.         cin >> a[i];
  61.     }
  62.     // dp(idx, s) -> dp state, number of subsequences starting at idx and sum of the subsequence is s
  63.     // dp(idx, s) = dp(idx+1, s) + dp(idx+1, s-a[idx])
  64.     int ans = 0;
  65.     for (int i = 1; i <= n; i++)
  66.     {
  67.         ans += dp(i, s);
  68.     }
  69.     cout << ans % mod << endl;
  70.     return;
  71. }
  72.  
  73. signed main()
  74. {
  75.     NeedForSpeed;
  76.     int t = 1;
  77.     // cin >> t;
  78.     while (t--)
  79.     {
  80.         solve();
  81.     }
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment