Advertisement
Mlxa

ALGO SegTree

Nov 30th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3. typedef unsigned long ui;
  4. typedef   long long   ll;
  5.  
  6. #define endl '\n'
  7. #define cout cout
  8. template <class A> void W (A h) { cout << h << endl; }
  9. template <class A, class... B> void W (A h, B... t) { cout << h << ' '; W(t...); }
  10. template <class A> void R (A& h) { cin >> h; }
  11. template <class A, class... B> void R (A& h, B... t) { cin >> h; R(t...); }
  12.  
  13. namespace seg {
  14.     const ll MaxN(1019), NE(0);
  15.     ll ARR[MaxN], VAL[4*MaxN], ADD[4*MaxN]; ui LB[4*MaxN], RB[4*MaxN];
  16.     ll f (ll a, ll b) { return a + b; }
  17.  
  18.     void build (ui v, ui lb, ui rb) {
  19.         LB[v] = lb, RB[v] = rb; ui mb = (lb + rb) / 2;
  20.         if (lb == rb) { VAL[v] = ARR[lb]; return; }
  21.         ui l = 2*v, r = l + 1;
  22.         build(l, lb, mb); build(r, mb+1, rb);
  23.         VAL[v] = f(VAL[l], VAL[r]);
  24.     }
  25.     ll get (ui v, ui ql, ui qr) {
  26.         ui lb = LB[v], rb = RB[v], mb = (lb + rb) / 2,
  27.         l = 2*v, r = l + 1; ll ret = NE;
  28.         W("Get:", v, ql, qr);
  29.         if (lb == ql && rb == qr)   return VAL[v];
  30.         else if (ql > qr)           return ret;
  31.         else {
  32.             if (qr > mb)  ret = f(ret, get(r, max(ql, mb+1), min(qr, rb) ));    
  33.             if (ql <= mb)   ret = f(ret, get(l, max(ql, lb), min(qr, mb) ));
  34.             return ret;
  35.         }
  36.     }
  37.     void update (ui v, ui add) {
  38.         if (LB[v] == RB[v]) ARR[LB[v]] += add;
  39.         while (v)       VAL[v] += add, v >>= 1;    
  40.     }
  41. }
  42.  
  43. template <class It> void read_it (It b, It e)
  44. { for (It i(b); i != e; ++i) cin>>*i; }
  45. template <class It> void write_it (It b, It e)
  46. { for (It i(b); i != e; ++i) cout<<*i<<' '; }
  47. ll n;
  48.  
  49. void read () {
  50.     using namespace seg;
  51.     ios::sync_with_stdio(0); // cin.tie(0);
  52.     R(n); read_it(ARR, ARR + n);
  53.     build(1, 0, n - 1);
  54.     write_it(VAL, VAL + 4*n);
  55. }
  56.  
  57. int main () {
  58.     read();
  59.     ll f, t;
  60.     while (cin>>f>>t)
  61.         W( seg::get(1, f, t) );
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement