fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4.  
  5. #define f first
  6. #define s second
  7. #define pb push_back
  8. #define ep emplace
  9. #define eb emplace_back
  10. #define lb lower_bound
  11. #define ub upper_bound
  12. #define all(x) x.begin(), x.end()
  13. #define rall(x) x.rbegin(), x.rend()
  14. #define uniquev(v) sort(all(v)), (v).resize(unique(all(v)) - (v).begin())
  15. #define mem(f,x) memset(f , x , sizeof(f))
  16. #define sz(x) (ll)(x).size()
  17. #define __lcm(a, b) (1ll * ((a) / __gcd((a), (b))) * (b))
  18. #define mxx *max_element
  19. #define mnn *min_element
  20. #define cntbit(x) __builtin_popcountll(x)
  21. #define len(x) (int)(x.length())
  22.  
  23. const int maxn = 2e6 + 100;
  24. int n, num[maxn], q[maxn], ok[maxn];
  25. ll m, sum = 0, f[maxn];
  26.  
  27. struct fake_set{
  28. priority_queue <ll, vector <ll>, greater <ll>> good, bad;
  29. int sz = 0;
  30. void add(ll x) {
  31. sz++;
  32. good.push(x);
  33. }
  34.  
  35. void er(ll x) {
  36. sz--;
  37. bad.push(x);
  38. }
  39.  
  40. ll get() {
  41. while (1) {
  42. ll t = good.top();
  43. ll v = sz(bad) ? bad.top() : -1e16;
  44.  
  45. if (t == v) {
  46. bad.pop();
  47. good.pop();
  48. } else {
  49. return t;
  50. }
  51. }
  52.  
  53. return 0;
  54. }
  55. };
  56.  
  57. int main() {
  58. ios_base::sync_with_stdio(0);
  59. cin.tie(0);
  60. cout.tie(0);
  61.  
  62. cin >> n >> m;
  63. mem(f, 0x3f);
  64.  
  65. f[0] = 0;
  66.  
  67. for(int i = 1; i <= n; ++i) {
  68. cin >> num[i];
  69. }
  70.  
  71. fake_set pq;
  72. int head = 0, tail = 0, pos = 0;
  73. ll sum = 0;
  74.  
  75. for (int i = 1; i <= n; ++i) {
  76. sum += num[i];
  77. while (sum > m)
  78. sum -= num[++pos];
  79.  
  80. while (head <= tail && q[head] <= pos) {
  81. ++head;
  82. if (ok[head]) {
  83. ok[head] = 0;
  84. pq.er(f[q[head - 1]] + num[q[head]]);
  85. }
  86. }
  87.  
  88. while (head <= tail && num[q[tail]] <= num[i]) {
  89. if (ok[tail]) {
  90. ok[tail] = 0;
  91. pq.er(f[q[tail - 1]] + num[q[tail]]);
  92. }
  93. --tail;
  94. }
  95.  
  96. q[++tail] = i;
  97. ok[tail] = 0;
  98.  
  99. if (tail > head) {
  100. pq.add(f[q[tail - 1]] + num[q[tail]]);
  101. ok[tail] = 1;
  102. }
  103.  
  104. f[i] = f[pos] + num[q[head]] - 1;
  105. if (pq.sz)
  106. f[i] = min(f[i], pq.get() - 1);
  107. }
  108.  
  109. cout << f[n] + n << '\n';
  110.  
  111. return 0;
  112. }
  113.  
Success #stdin #stdout 0.01s 19872KB
stdin
Standard input is empty
stdout
0