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 79 80 81 82 83
| const int N = 5e5 + 10, M = 3e7 + 10; struct Node { int s[2], v, w, sz; void init (int k) { s[0] = s[1] = 0, v = k, w = rand(), sz = 1; } } tr[M]; int m, rt[N], idx; void pushup (int x) { tr[x].sz = tr[tr[x].s[0]].sz + tr[tr[x].s[1]].sz + 1; } int merge (int x, int y) { if (!x || !y) return x + y; if (tr[x].w < tr[y].w) { tr[++idx] = tr[x]; x = idx; tr[x].s[1] = merge(tr[x].s[1], y); pushup(x); return x; } else { tr[++idx] = tr[y]; y = idx; tr[y].s[0] = merge(x, tr[y].s[0]); pushup(y); return y; } } void split (int u, int k, int &x, int &y) { if (!u) return void(x = y = 0); tr[++idx] = tr[u], u = idx; if (tr[u].v <= k) x = u, split(tr[u].s[1], k, tr[u].s[1], y); else y = u, split(tr[u].s[0], k, x, tr[u].s[0]); pushup(u); } void insert (int &u, int k) { int x, y; split(u, k, x, y); tr[++idx].init(k); u = merge(merge(x, idx), y); } void remove (int &u, int k) { int x, y, z; split(u, k, x, z); split(x, k - 1, x, y); y = merge(tr[y].s[0], tr[y].s[1]); u = merge(merge(x, y), z); } int rnk (int &u, int k) { int x, y; split(u, k - 1, x, y); int res = tr[x].sz + 1; u = merge(x, y); return res; } int kth(int u, int k) { while (u) { if (k <= tr[tr[u].s[0]].sz) u = tr[u].s[0]; else if (k == tr[tr[u].s[0]].sz + 1) return u; else k -= tr[tr[u].s[0]].sz + 1, u = tr[u].s[1]; } } int pre (int &u, int k) { int x, y; split(u, k - 1, x, y); int res = kth(x, tr[x].sz); u = merge(x,y); return res; } int nxt(int &u, int k) { int x, y; split(u, k, x, y); int res = kth(y, 1); u = merge(x, y); return res; }
|