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
| #include <bits/stdc++.h> #define MAXN 100005 using namespace std;
int n, ans, tot, root;
struct Treap {int l, r, val, rank, cnt, size;} t[MAXN];
void update(int p) { t[p].size=t[t[p].l].size+t[t[p].r].size+t[p].cnt; }
int findrank(int p, int val) { if(p==0) return 0; if(val==t[p].val) return t[t[p].l].size+1; if(val<t[p].val) return findrank(t[p].l, val); return findrank(t[p].r, val)+t[t[p].l].size+t[p].cnt; }
int findval(int p, int rank) { if(p==0) return 0; if(t[t[p].l].size>=rank) return findval(t[p].l, rank); if(t[t[p].l].size+t[p].cnt>=rank) return t[p].val; return findval(t[p].r, rank-t[t[p].l].size-t[p].cnt); }
void zig(int &p) { int q=t[p].l; t[p].l=t[q].r; t[q].r=p; p=q; update(t[p].r); update(p); }
void zag(int &p) { int q=t[p].r; t[p].r=t[q].l; t[q].l=p; p=q; update(t[p].l); update(p); }
void insert(int &p, int val) { if(p==0) { t[++tot].val=val; t[tot].rank=rand(); t[tot].cnt=t[tot].size=1; p=tot; return; } if(val==t[p].val) t[p].cnt++; if(val<t[p].val) { insert(t[p].l, val); if(t[p].rank<t[t[p].l].rank) zig(p); } if(val>t[p].val) { insert(t[p].r, val); if(t[p].rank<t[t[p].r].rank) zag(p); } update(p); }
void remove(int &p, int val) { if(p==0) return; if(val==t[p].val) { if(t[p].cnt>1) { t[p].cnt--; update(p); return; } if(t[p].l*t[p].r==0) p=t[p].l+t[p].r; else if(t[t[p].l].rank>t[t[p].r].rank) zig(p), remove(p, val); else zag(p), remove(p, val); } if(val<t[p].val) remove(t[p].l, val); if(val>t[p].val) remove(t[p].r, val); update(p); }
void findpre(int p, int x) { if(p==0) return; if(t[p].val<x) ans=p, findpre(t[p].r, x); else findpre(t[p].l, x); }
void findnext(int p, int x) { if(p==0) return; if(t[p].val>x) ans=p, findnext(t[p].l,x); else findnext(t[p].r,x); }
int main() { scanf("%d", &n); for(int i=1; i<=n; i++) { int opt, x; scanf("%d%d", &opt, &x); if(opt==1) insert(root, x); if(opt==2) remove(root, x); if(opt==3) printf("%d\n", findrank(root, x)); if(opt==4) printf("%d\n", findval(root, x)); if(opt==5) ans=0, findpre(root, x), printf("%d\n", t[ans].val); if(opt==6) ans=0, findnext(root, x), printf("%d\n", t[ans].val); } }
|