1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| struct WBLT { int cnt, root; int val[M], sz[M], ls[M], rs[M]; WBLT() { new_node(root, 1e9); } inline bool is_leaf(int x) { return !(ls[x] || rs[x]); } inline void push_up(int x) { if (is_leaf(x)) return; val[x] = max(val[ls[x]], val[rs[x]]); sz[x] = sz[ls[x]] + sz[rs[x]]; } inline void new_node(int &x, int k) { x = ++cnt; val[x] = k, sz[x] = 1; } inline void rotate(int x, bool opt) { if (!opt) { int rson = rs[x]; rs[x] = ls[x], ls[x] = ls[rs[x]]; ls[rs[x]] = rs[rs[x]], rs[rs[x]] = rson; } else { int lson = ls[x]; ls[x] = rs[x], rs[x] = rs[ls[x]]; rs[ls[x]] = ls[ls[x]], ls[ls[x]] = lson; } push_up(ls[x]), push_up(rs[x]); } inline void maintain(int x) { if (is_leaf(x)) return; if (sz[ls[x]] >= sz[rs[x]] * 4) rotate(x, 0); if (sz[rs[x]] >= sz[ls[x]] * 4) rotate(x, 1); } void insert(int x, int k) { if (is_leaf(x)) { new_node(ls[x], min(val[x], k)); new_node(rs[x], max(val[x], k)); push_up(x); return; } if (k <= val[ls[x]]) insert(ls[x], k); else insert(rs[x], k); push_up(x), maintain(x); } void erase(int x, int fa, int k) { if (is_leaf(x)) { if (!fa) return; int son = ls[fa] == x ? rs[fa] : ls[fa]; val[fa] = val[son], sz[fa] = sz[son]; ls[fa] = ls[son], rs[fa] = rs[son]; return; } if (k <= val[ls[x]]) erase(ls[x], x, k); else erase(rs[x], x, k); push_up(x), maintain(x); } int rank(int x, int k) { if (is_leaf(x)) return 1 + (k > val[x]); if (k <= val[ls[x]]) return rank(ls[x], k); else return sz[ls[x]] + rank(rs[x], k); } int k_th(int x, int k) { if (is_leaf(x)) return x; if (k <= sz[ls[x]]) return k_th(ls[x], k); else return k_th(rs[x], k - sz[ls[x]]); } int next(int rt, int k, bool opt) { int rk = rank(rt, k), rk2 = rank(rt, k+1); if (!opt && rk == 1) return -INF; if (opt && rk2 > sz[rt]) return INF; return val[k_th(rt, opt ? rk2 : rk - 1)]; } };
|