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
| #include<bits/stdc++.h> using namespace std; const int N = 100001, INF = 1e7 + 1; int rt, son[N][2], val[N], cnt[N], sz[N], tot; inline int newnode(int x){ val[++tot] = x; cnt[tot] = 1; sz[tot] = 1; return tot; } inline void pushup(int x){ sz[x] = sz[son[x][0]] + sz[son[x][1]] + cnt[x]; } int Insert(int u, int x){ if (!u) return newnode(x); if (val[u] == x) return ++cnt[u], u; if (val[u] < x) son[u][1] = Insert(son[u][1], x); else son[u][0] = Insert(son[u][0], x); return pushup(u), u; } void Delete(int u, int x){ if (val[u] == x) --cnt[u]; else if (val[u] < x) Delete(son[u][1], x); else Delete(son[u][0], x); return pushup(u); } int Rank(int u, int x){ if (!u) return 1; if (val[u] < x) return sz[son[u][0]] + cnt[u] + Rank(son[u][1], x); else if (val[u] == x) return sz[son[u][0]] + 1; else return Rank(son[u][0], x); } int QueryK(int u, int k){ if (k <= sz[son[u][0]]) return QueryK(son[u][0], k); if (k <= sz[son[u][0]] + cnt[u]) return val[u]; return QueryK(son[u][1], k - sz[son[u][0]] - cnt[u]); } signed main(){ int n; scanf("%d", &n); while (n--){ int opt, x; scanf("%d%d", &opt, &x); if (opt == 1) rt = Insert(rt, x); else if (opt == 2) Delete(rt, x); else if (opt == 3) printf("%d\n", Rank(rt, x)); else if (opt == 4) printf("%d\n", QueryK(rt, x)); else if (opt == 5) printf("%d\n", QueryK(rt, Rank(rt, x) - 1)); else if (opt == 6) printf("%d\n", QueryK(rt, Rank(rt, x + 1))); } return 0; }
|