扔板跑……
1 #include<bits/stdc++.h> 2 #define N 100010 3 #define mp make_pair 4 using namespace std; 5 typedef pair<int,int> par; 6 int n,x,rt; 7 struct Treap_Without_rotate{ 8 int ls[N],rs[N],rnd[N],val[N],size[N],cnt; 9 inline void pushup(int x){size[x]=size[ls[x]]+size[rs[x]]+1;} 10 par split(int k,int x){ 11 if(!x)return mp(0,k);int l=ls[k],r=rs[k]; 12 if(x==size[l]){ls[k]=0;pushup(k);return mp(l,k);} 13 if(x==size[l]+1){rs[k]=0;pushup(k);return mp(k,r);} 14 if(x<size[l]){ 15 par tmp=split(l,x); 16 ls[k]=tmp.second;pushup(k);return mp(tmp.first,k); 17 } 18 par tmp=split(r,x-size[l]-1); 19 rs[k]=tmp.first;pushup(k);return mp(k,tmp.second); 20 } 21 int merge(int x,int y){ 22 if(x==0||y==0)return x+y; 23 if(rnd[x]<rnd[y]){rs[x]=merge(rs[x],y);pushup(x);return x;} 24 else{ls[y]=merge(x,ls[y]);pushup(y);return y;} 25 } 26 int queryrank(int x,int k){ 27 int ans=0,tmp=(int)1e9; 28 while(k){ 29 if(x==val[k])tmp=min(tmp,ans+size[ls[k]]+1); 30 if(x>val[k])ans+=size[ls[k]]+1,k=rs[k]; 31 else k=ls[k]; 32 } 33 return tmp==(int)1e9?ans:tmp; 34 } 35 int find(int x,int k){ 36 for(;;){ 37 if(size[ls[k]]==x-1)return val[k]; 38 if(size[ls[k]]>x-1)k=ls[k]; 39 else x=x-size[ls[k]]-1,k=rs[k]; 40 } 41 } 42 int querypre(int x,int k){ 43 int ans=-(int)1e9; 44 while(k){ 45 if(val[k]<x)ans=max(ans,val[k]),k=rs[k]; 46 else k=ls[k]; 47 }return ans; 48 } 49 int querysub(int x,int k){ 50 int ans=(int)1e9; 51 while(k){ 52 if(val[k]>x)ans=min(ans,val[k]),k=ls[k]; 53 else k=rs[k]; 54 }return ans; 55 } 56 void ins(int x){ 57 int k=queryrank(x,rt);par tmp=split(rt,k); 58 val[++cnt]=x;rnd[cnt]=rand();size[cnt]=1; 59 rt=merge(tmp.first,cnt);rt=merge(rt,tmp.second); 60 } 61 void del(int x){ 62 int k=queryrank(x,rt);par t1=split(rt,k),t2=split(t1.first,k-1); 63 rt=merge(t2.first,t1.second); 64 } 65 }T; 66 inline int read(){ 67 int f=1,x=0;char ch; 68 do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9'); 69 do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9'); 70 return f*x; 71 } 72 int main(){ 73 n=read();srand(19260817); 74 for(int i=1;i<=n;i++){ 75 int opt=read(),x=read(); 76 if(opt==1)T.ins(x); 77 if(opt==2)T.del(x); 78 if(opt==3)printf("%d ",T.queryrank(x,rt)); 79 if(opt==4)printf("%d ",T.find(x,rt)); 80 if(opt==5)printf("%d ",T.querypre(x,rt)); 81 if(opt==6)printf("%d ",T.querysub(x,rt)); 82 } 83 return 0; 84 }