bhupixb

Maximum subarray sum with update

Oct 19th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5.  
  6. #define int long long
  7. #define sz(x) ((int)x.size())
  8. #define rep(i,a,n) for (int i = a; i <= n; ++i)
  9. #define all(v) v.begin(), v.end()
  10. #define pb push_back
  11. #define E cout << '\n'
  12.  
  13. const int mod = 1e9 + 7;
  14. const int N = 1e5 + 5;
  15.  
  16. int a[N];
  17.  
  18. struct node {
  19. int mxPreSum, mxSuffSum, totalSum, maxSubSum;
  20. node() {
  21. mxSuffSum = mxPreSum = 0;
  22. totalSum = 0, maxSubSum = 0;
  23. }
  24. node(int a,int b,int c,int d) {
  25. mxPreSum = a, mxSuffSum = b;
  26. totalSum = c, maxSubSum = d;
  27. }
  28.  
  29. }tree[N<<2];
  30.  
  31. inline node merge(node lc, node rc) {
  32. node now;
  33. now.mxPreSum = max(lc.mxPreSum, lc.totalSum+rc.mxPreSum);
  34. now.mxSuffSum = max(rc.mxSuffSum, rc.totalSum+lc.mxSuffSum);
  35. now.totalSum = lc.totalSum+rc.totalSum;
  36. now.maxSubSum = max({lc.maxSubSum,rc.maxSubSum,lc.mxSuffSum+rc.mxPreSum});
  37. return now;
  38. }
  39.  
  40. void build(int l, int r, int x) {
  41. if (l == r) {
  42. tree[x] = node(a[l],a[l],a[l],a[l]);
  43. return;
  44. }
  45. int mid=l+r>>1LL, lc=mid+mid, rc=lc|1;
  46. build(l,mid,lc);
  47. build(mid+1,r,rc);
  48. tree[x]=merge(tree[lc],tree[rc]);
  49. }
  50.  
  51. void update(int l, int r, int pos, int val, int x) {
  52. if (pos < l || pos > r)
  53. return;
  54. if (l == r && pos == l) {
  55. tree[x] = node(val,val,val,val);
  56. return;
  57. }
  58. int mid=l+r>>1LL, lc=mid+mid, rc=lc|1;
  59. update(l,mid,pos,val,lc);
  60. update(mid+1,r,pos,val,rc);
  61. tree[x] = merge(tree[lc], tree[rc]);
  62. }
  63.  
  64. inline void solve() {
  65. int n, k, ans = 1e8;
  66. cin >> n >> k;
  67. rep(i,1,n) {
  68. cin >> a[i];
  69. }
  70. int lo,hi,mid;
  71. build(1,n,1);
  72. rep(i,1,n) {
  73. lo = -1e8, hi = 1e8;
  74. while (lo <= hi) {
  75. mid = lo + hi>>1LL;
  76. update(1,n,i,mid,1);
  77. if (tree[1].maxSubSum < k)
  78. lo = mid+1;
  79. else
  80. hi = mid-1;
  81. }
  82. update(1,n,i,a[i],1);
  83. ans = min(ans, hi+1);
  84. }
  85. cout << ans << '\n';
  86. }
  87. signed main() {
  88. ios_base::sync_with_stdio(0);
  89. cin.tie(NULL);
  90. cout.tie(NULL);
  91. int t = 1;
  92. //cin >> t; while(t--)
  93. solve();
  94. return 0;
  95. }
  96. Statistics
  97. Difficulty: Medium
  98.  
  99. Time Complexity:
  100. N(logN)log(2e8)
  101.  
  102. Required Knowledge: Segment Trees, Binary Search
  103.  
  104. Publish Date: Oct 05 2019
Add Comment
Please, Sign In to add comment