Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. template <class T>
  2. struct SegmentTree {
  3.     struct vertex{
  4.         int l, r;
  5.         T d;  
  6.         int id;
  7.  
  8.         inline int Lchild() { return id * 2; }
  9.         inline int Rchild() { return id * 2 + 1;};
  10.     };
  11.  
  12.     vector<vertex> t;
  13.  
  14.     void build(int id, int l, int r){
  15.         t[id] = {l, r, T(), id};
  16.         if (l == r){
  17.             return;
  18.         }
  19.         int m = (l + r) / 2;
  20.         build(t[id].Lchild(), l, m);
  21.         build(t[id].Rchild(), m + 1, r);
  22.     }
  23.  
  24.     SegmentTree(int n_){
  25.         t.resize(n_ * 4);
  26.         build(1, 0, n_ - 1);
  27.     }
  28.  
  29.     template <class BinaryOperation>
  30.     void update(int id, BinaryOperation op){
  31.         if (t[id].l == t[id].r)
  32.             return;
  33.         t[id].d = op(t[t[id].Lchild()].d, t[t[id].Rchild()].d);
  34.     }
  35.  
  36.     template <class BinaryOperation>
  37.     void push(int id, BinaryOperation op){
  38.         if (t[id].l == t[id].r)
  39.             return;
  40.         t[t[id].Lchild()].d.push(t[id].d);
  41.         t[t[id].Rchild()].d.push(t[id].d);
  42.         t[id].d.pushclear();
  43.         update(id, op);
  44.     }
  45.  
  46.     template <class UnaryOperation, class BinaryOperation>
  47.     void process(int id, int l, int r, UnaryOperation op, BinaryOperation upd) {
  48.         if (t[id].l > r || t[id].r < l) {
  49.             return;
  50.         }
  51.         push(id, upd);
  52.         if (l <= t[id].l && t[id].r <= r) {
  53.             op(t[id].d);
  54.             push(id, upd);
  55.             return;
  56.         }
  57.         process(t[id].Lchild(), l, r, op, upd);
  58.         process(t[id].Rchild(), l, r, op, upd);
  59.         update(id, upd);
  60.     }
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement