照着蓝书写的
#include<bits/stdc++.h>
#include<time.h>
using namespace std;
const int maxn=1e5+5;
const int INF=0x7fffffff;
struct node{
int lc,rc;
int val,dat;
int num,size;
}tree[maxn];
int n,cnt,rt;
int add(int val){
tree[++cnt].val=val;
tree[cnt].dat=rand();
tree[cnt].num=tree[cnt].size=1;
return cnt;
}
void upDate(int p){
tree[p].size=tree[tree[p].lc].size+tree[tree[p].rc].size+tree[p].num;
}
void build(){
add(-INF);add(INF);
rt=1;
tree[1].rc=2;
upDate(rt);
}
int rankfindbyval(int p,int val){
if(p==0)
return 0;
if(val==tree[p].val)
return tree[tree[p].lc].size+1;
if(val<tree[p].val)
return rankfindbyval(tree[p].lc,val);
return rankfindbyval(tree[p].rc,val)+tree[tree[p].lc].size+tree[p].num;
}
int valfindbyrank(int p,int rank){
if(p==0)
return INF;
if(tree[tree[p].lc].size>=rank)
return valfindbyrank(tree[p].lc,rank);
if(tree[tree[p].lc].size+tree[p].num>=rank)
return tree[p].val;
return valfindbyrank(tree[p].rc,rank-tree[tree[p].lc].size-tree[p].num);
}
void zig(int &p){
int q=tree[p].lc;
tree[p].lc=tree[q].rc,tree[q].rc=p,p=q;
upDate(tree[p].rc);
upDate(p);
}
void zag(int &p){
int q=tree[p].rc;
tree[p].rc=tree[q].lc,tree[q].lc=p,p=q;
upDate(tree[p].lc);
upDate(p);
}
void inst(int &p,int val){
if(p==0){
p=add(val);
return;
}
if(val==tree[p].val){
tree[p].num++;upDate(p);
return;
}
if(val<tree[p].val){
inst(tree[p].lc,val);
if(tree[p].dat<tree[tree[p].lc].dat){
zig(p);
}
}
else{
inst(tree[p].rc,val);
if(tree[p].dat<tree[tree[p].rc].dat){
zag(p);
}
}
upDate(p);
}
int getpre(int val){
int ans=1;
int p=rt;
while(p){
if(val==tree[p].val){
if(tree[p].lc>0){
p=tree[p].lc;
while(tree[p].rc>0)p=tree[p].rc;
ans=p;
}
break;
}
if(tree[p].val<val && tree[p].val>tree[ans].val)ans=p;
p=val<tree[p].val? tree[p].lc:tree[p].rc;
}
return tree[ans].val;
}
int getnxt(int val){
int ans=2;
int p=rt;
while(p){
if(val==tree[p].val){
if(tree[p].rc>0){
p=tree[p].rc;
while(tree[p].lc>0)p=tree[p].lc;
ans=p;
}
break;
}
if(tree[p].val>val&&tree[p].val<tree[ans].val)ans=p;
p=val<tree[p].val? tree[p].lc:tree[p].rc;
}
return tree[ans].val;
}
void del(int &p,int val){
if(p==0){
return;
}
if(val==tree[p].val){
if(tree[p].num>1){
tree[p].num--;
upDate(p);
return;
}
if(tree[p].lc||tree[p].rc){
if(tree[p].rc==0||tree[tree[p].lc].dat>tree[tree[p].rc].dat){
zig(p);
del(tree[p].rc,val);
}
else{
zag(p);
del(tree[p].lc,val);
}
upDate(p);
}
else{
p=0;
}
return;
}
val<tree[p].val? del(tree[p].lc,val):del(tree[p].rc,val);
upDate(p);
}
int main(){
build();
srand((unsigned int)time(NULL));
cin>>n;
for(int i=1;i<=n;i++){
int opt,x;
cin>>opt>>x;
switch(opt){
case 1:inst(rt,x);break;
case 2:del(rt,x);break;
case 3:printf("%lld\n",rankfindbyval(rt,x)-1);break;
case 4:printf("%lld\n",valfindbyrank(rt,x+1));break;
case 5:printf("%lld\n",getpre(x));break;
case 6:printf("%lld\n",getnxt(x));break;
}
}
return 0;
}