
1 #define lch(x) tr[x].son[0] 2 #define rch(x) tr[x].son[1] 3 const int N = 1e5 + 100; 4 int tot = 0, root; 5 struct Node{ 6 int son[2], pre, sz; 7 void init(){ 8 sz = 1; 9 son[0] = son[1] = pre = 0; 10 } 11 }tr[N]; 12 13 void Push_Rev(int x){ 14 if(!x) return ; 15 swap(lch(x), rch(x)); 16 tr[x].rev ^= 1; 17 } 18 void Push_up(int x){ 19 if(!x) return; 20 tr[x].sz = tr[lch(x)].sz + tr[rch(x)].sz + 1; 21 } 22 23 void Push_Down(int x){ 24 if(tr[x].rev){ 25 tr[x].rev = 0; 26 Push_Rev(lch(x)); 27 Push_Rev(rch(x)); 28 } 29 } 30 31 void Reverse(int l, int r){ 32 int pl = Find(l, root); 33 int pr = Find(r+2, root); 34 Splay(pl, 0); 35 Splay(pr, pl); 36 Push_Rev(tr[pr].son[0]); 37 Push_Up(tr[pr].son[0]); 38 Push_Up(pr); 39 Push_Up(pl); 40 } 41 42 int build(int ll, int rr){ 43 int p = 0, x; 44 for(int i = rr; i >= ll; i--){ 45 x = ++tot; 46 tr[x].init(); 47 tr[x].son[1] = p; 48 tr[p].pre = x; 49 Push_Up(x); 50 p = x; 51 } 52 return x; 53 } 54 55 void rotate(int x){ 56 int y = tr[x].pre; 57 int z = tr[y].pre; 58 int k = x == rch(y); 59 tr[x].pre = z; 60 tr[z].son[y == rch(z)] = x; 61 tr[y].son[k] = tr[x].son[k^1]; 62 tr[tr[y].son[k]].pre = y; 63 tr[x].son[k^1] = y; 64 tr[y].pre = x; 65 Push_up(y); 66 } 67 68 void splay(int x, int goal){ 69 while(tr[x].pre != goal){ 70 int y = tr[x].pre; 71 int z = tr[y].pre; 72 if(z != goal){ 73 if((lch(y) == x) ^ (lch(z) == y)) rotate(x); ///x和y分别是y和z的同一段的儿子 74 else rotate(y); 75 } 76 rotate(x); 77 } 78 if(!goal) root = x; 79 Push_up(x); 80 } 81 int Find(int num, int x){ 82 Push_Down(x); 83 if(num == tr[lch(x)].sz + 1) return x; 84 if(num <= tr[lch(x)].sz) return Find(num, lch(x)); 85 return Find(num - tr[lch(x)].sz - 1, rch(x)); 86 } 87 void Insert_point(LL v, LL z){ 88 int p = root, ff = 0; 89 while(p && tr[p].val != v){ 90 ff = p; 91 p = tr[p].son[ tr[p].val < v]; 92 } 93 if(p){ 94 tr[p].szz += z; 95 } 96 else { 97 p = ++tot; 98 if(ff) tr[ff].son[ tr[ff].val < v] = p; 99 tr[p].init(v, z); 100 tr[p].pre = ff; 101 } 102 splay(p, 0); 103 } 104 105 void Collect(int x){ 106 if(tr[x].son[0]) Clear(tr[x].son[0]); 107 if(tr[x].son[1]) Clear(tr[x].son[1]); 108 sta[++top] = x; 109 } 110 void Delete_tree(int l, int r){ 111 int pl = Find(l, root); 112 int pr = Find(r+2, root); 113 Splay(pl, 0); 114 Splay(pr, pl); 115 Collect(tr[pr].son[0]); 116 tr[pr].son[0] = 0; 117 Push_Up(pr); 118 Push_Up(pl); 119 } 120 121 void dfs(int x){ 122 Push_down(x); 123 if(lch(x)) dfs(lch(x)); 124 printf("%d ", tr[x].val); 125 if(rch(x)) dfs(rch(x)); 126 }