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 143 144 145
| #include<bits/stdc++.h> using namespace std; const int inf=1e9; int ch[1000005][2],cnt[1000005],size[1000005],key[1000005],rd[1000005]; int sz,n,root; int newpoint(int x) { sz++; key[sz]=x; rd[sz]=rand(); size[sz]=1; cnt[sz]=1; return sz; } void pushup(int x) { if(x) { size[x]=cnt[x]; if(ch[x][0])size[x]+=size[ch[x][0]]; if(ch[x][1])size[x]+=size[ch[x][1]]; } } void build() { root=newpoint(-inf),ch[root][1]=newpoint(inf); pushup(root); } void rotate(int &x,int d) { int son=ch[x][d^1]; ch[x][d^1]=ch[son][d]; ch[son][d] = x; pushup(x),pushup(son); x=son; } void insert(int &x,int val) { if(!x) { x=newpoint(val); return ; } if(key[x]==val) { cnt[x]++; pushup(x); return ; } int d=key[x]<val; insert(ch[x][d],val); if(rd[x]< rd[ch[x][d]]) rotate(x,d^1); pushup(x); } void del(int &x,int val) { if(!x) return ; if(key[x]==val) { if(cnt[x]>1) { cnt[x]--; pushup(x); return ; } bool d=rd[ch[x][0]]>rd[ch[x][1]]; if(ch[x][0]||ch[x][1]) { if(!ch[x][1]||d) rotate(x,1),del(ch[x][1],val); else rotate(x,0),del(ch[x][0],val); pushup(x); } else x=0; } else { del(ch[x][key[x]<val],val); pushup(x); } } int rnk(int x,int val) { if(!x)return 0; if(key[x]==val) return size[ch[x][0]]+1; if(key[x]>val) return rnk(ch[x][0],val); return rnk(ch[x][1],val)+size[ch[x][0]]+cnt[x]; } int kth(int x,int k) { if(!x)return inf; if(k<=size[ch[x][0]]) return kth(ch[x][0],k); if(k<=size[ch[x][0]]+cnt[x]) return key[x]; return kth(ch[x][1],k-size[ch[x][0]]-cnt[x]); } int pre(int x,int val) { int res=-inf; while(x) { if(key[x]>=val) x=ch[x][0]; else res=key[x],x=ch[x][1]; } return res; } int next(int x,int val) { int res=inf; while(x) { if(key[x]<=val) x=ch[x][1]; else res=key[x],x=ch[x][0]; } return res; } signed main() { srand(time(0)),srand(rand()),srand(rand()+19260817),srand(time(0)+rand()),srand(rand()*rand()),srand(rand()+359003647); scanf("%d",&n); build(); for(int i=1,opt,x;i<=n;i++) { scanf("%d%d",&opt,&x); switch(opt) { case 1:insert(root,x);break; case 2:del(root,x);break; case 3:printf("%d\n",rnk(root,x)-1);break; case 4:printf("%d\n",kth(root,x+1));break; case 5:printf("%d\n",pre(root,x));break; case 6:printf("%d\n",next(root,x));break; } } }
|