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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| #include <cstdio> using namespace std; const int N = 1e5 + 10; struct Node { int v, p, s[2], sz; } tr[N]; bool vis[N]; int n, m, rt, idx; void pushup(int x) { tr[x].sz = tr[tr[x].s[0]].sz + 1 + tr[tr[x].s[1]].sz; } void rotate(int x) { int y = tr[x].p, z = tr[y].p; int k = tr[y].s[1] == x; tr[z].s[tr[z].s[1] == y] = x; tr[x].p = z; tr[y].s[k] = tr[x].s[k ^ 1]; tr[tr[x].s[k ^ 1]].p = y; tr[x].s[k ^ 1] = y; tr[y].p = x; pushup(x); pushup(y); } void splay(int x, int k) { while (tr[x].p != k) { int y = tr[x].p, z = tr[y].p; if (z != k) if ((tr[y].s[1] == x) ^ (tr[z].s[1] == y)) rotate(x); else rotate(y); rotate(x); } if (!k) rt = x; } void insert(int x) { int u = rt, p; while (u) { p = u; u = tr[u].s[x > tr[u].v]; } u = ++idx; if (p) tr[p].s[x > tr[p].v] = u; tr[u].v = x; tr[u].sz = 1; tr[u].p = p; splay(u, 0); } int pre(int x) { int u = rt, res, v = rt; while (u) { v = u; if (tr[u].v < x) { res = u; u = tr[u].s[1]; } else u = tr[u].s[0]; } splay(v, 0); return res; } int nxt(int x) { int u = rt, res, v = rt; while (u) { v = u; if (tr[u].v > x) { res = u; u = tr[u].s[0]; } else u = tr[u].s[1]; } splay(v, 0); return res; } void remove(int x) { int l = pre(x), r = nxt(x); splay(l, 0); splay(r, l); tr[tr[r].s[0]].sz = 0; tr[tr[r].s[0]].p = 0; tr[r].s[0] = 0; splay(r, 0); } void init() { rt = ++idx; tr[rt].p = 0; tr[rt].sz = 1; tr[rt].v = 0; insert(n + 1); } int top, stk[N]; int main() { scanf("%d%d", &n, &m); init(); for (char op[2]; m; m--) { scanf("%s", op); if (op[0] == 'D') { int x; scanf("%d", &x); insert(x); stk[++top] = x; vis[x] = true; } else if (op[0] == 'R') { vis[stk[top]] = false; remove(stk[top--]); } else if (op[0] == 'Q') { int x; scanf("%d", &x); if (vis[x]) puts("0"); else printf("%d\n", tr[nxt(x)].v - tr[pre(x)].v - 1); } } return 0; }
|