tien_noob

Segment Tree with Lazy Propagation

May 5th, 2021 (edited)
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int N = 5e4;
  4. struct T
  5. {
  6.     long long lazy, val;
  7. };
  8. T Tree[4*N+1];
  9. int n, m, q;
  10. void down(int id)
  11. {
  12.     long long up = Tree[id].lazy;
  13.     Tree[id*2].lazy += up;
  14.     Tree[id*2].val += up;
  15.  
  16.     Tree[id*2 + 1].lazy += up;
  17.     Tree[id*2 + 1].val += up;
  18.  
  19.     Tree[id].lazy = 0;
  20. }
  21. long long GetMax(int id, int TreeL, int TreeR, int l, int r)
  22. {
  23.     if (l > r)
  24.     {
  25.         return 0;
  26.     }
  27.     if (l == TreeL && r == TreeR)
  28.     {
  29.         return Tree[id].val;
  30.     }
  31.     down(id);
  32.     int mid = (TreeL + TreeR)/2;
  33.     return max(GetMax(id * 2, TreeL, mid, l, min(mid, r)), GetMax(id * 2 + 1, mid + 1, TreeR, max(l, mid + 1), r));
  34. }
  35. void Update(int id, int TreeL, int TreeR, int l, int r, long long add)
  36. {
  37.     if (l > r)
  38.     {
  39.         return ;
  40.     }
  41.     if (l == TreeL && r == TreeR)
  42.     {
  43.         Tree[id].lazy += add;
  44.         Tree[id].val += add;
  45.         return ;
  46.     }
  47.     down(id);
  48.     int mid = (TreeL + TreeR)/2;
  49.     Update(id * 2, TreeL, mid, l, min(mid, r), add);
  50.     Update(id * 2 + 1, mid + 1, TreeR, max(l, mid + 1), r, add);
  51.     Tree[id].val = max(Tree[id*2].val, Tree[id*2 + 1].val);
  52. }
  53. void read()
  54. {
  55.    cin >> n >> m;
  56.    int l, r, k;
  57.    for (int i = 1; i <= m; ++ i)
  58.    {
  59.        cin >> l >> r >> k;
  60.        Update(1, 1, n, l, r, k);
  61.    }
  62. }
  63. void solve()
  64. {
  65.    int l, r;
  66.    cin >> q;
  67.    while (q--)
  68.    {
  69.        cin >> l >> r;
  70.        cout << GetMax(1, 1, n, l, r) << '\n';
  71.    }
  72. }
  73. int main()
  74. {
  75.     ios_base::sync_with_stdio(false);
  76.     cin.tie(nullptr);
  77.     read();
  78.     solve();
  79. }
  80.  
Add Comment
Please, Sign In to add comment