Advertisement
vlatkovski

Simple segment tree (good)

Apr 6th, 2019
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef pair<int, int> pi;
  5. typedef vector<int> vi;
  6.  
  7.  
  8.  
  9. const int MAXN = 300005;
  10.  
  11. int n;
  12. int arr[MAXN];
  13.  
  14. int st[4*MAXN];
  15.  
  16. void build(int v, int tl, int tr) {
  17.     if (tl == tr) {
  18.         st[v] = arr[tl];
  19.     } else {
  20.         int tm = (tl + tr) / 2;
  21.         build(2*v, tl, tm);
  22.         build(2*v+1, tm+1, tr);
  23.         st[v] = st[2*v] + st[2*v+1];
  24.     }
  25. }
  26.  
  27. int sum(int v, int tl, int tr, int l, int r) {
  28.     if (l > r || l > tr || r < tl) return 0;
  29.     if (l <= tl && tr <= r) return st[v];
  30.     int tm = (tl + tr) / 2;
  31.     return sum(2*v, tl, tm, l, r) + sum(2*v+1, tm+1, tr, l, r);
  32. }
  33.  
  34. void update(int v, int tl, int tr, int pos, int val) {
  35.     if (tl == tr) {
  36.         st[v] = val;
  37.     } else {
  38.         int tm = (tl + tr) / 2;
  39.         if (pos <= tm) {
  40.             update(2*v, tl, tm, pos, val);
  41.         } else {
  42.             update(2*v+1, tm+1, tr, pos, val);
  43.         }
  44.         st[v] = st[2*v] + st[2*v+1];
  45.     }
  46. }
  47.  
  48. void Main() {
  49.     cout << "Enter N, the size of the array, and then N numbers\n";
  50.     cin >> n;
  51.     for (int i = 0; i < n; ++i) {
  52.         cin >> arr[i];
  53.     }
  54.     build(1, 0, n-1);
  55.     cout << "First type of query:\n";
  56.     cout << "1 l r\n";
  57.     cout << "--> Get the sum from l to r (0-indexed)\n";
  58.     cout << "Second type of query:\n";
  59.     cout << "2 x v\n";
  60.     cout << "--> Update element at position x to new value v\n";
  61.     while (true) {
  62.         int t;
  63.         cin >> t;
  64.         if (t == 1) {
  65.             int l, r;
  66.             cin >> l >> r;
  67.             cout << "Sum(" << l << ", " << r << ") = " << sum(1, 0, n-1, l, r) << "\n";
  68.         } else if (t == 2) {
  69.             int x, v;
  70.             cin >> x >> v;
  71.             update(1, 0, n-1, x, v);
  72.         } else {
  73.             cout << "Could not understand query\n";
  74.         }
  75.     }
  76. }
  77.  
  78. int main() {
  79. //    ios::sync_with_stdio(false);
  80. //    cin.tie(0);
  81.     #ifdef _DEBUG
  82. //    freopen("in.txt", "r", stdin);
  83. //    freopen("out.txt", "w", stdout);
  84.     #endif
  85.     #ifndef _DEBUG
  86.     #endif
  87.     Main();
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement