#include<iostream>
#include<cstdio>
using namespace std;
int root,tot;
struct bst
{int v,l,r,vnum,lnum;bst(){v=l=r=vnum=lnum=0;}void nw(int a){v=a;vnum=1;lnum=0;l=r=0;}
}tree[1000010];
struct nd
{int v,idx,fa;nd(){v=idx=fa=0;}nd(int a,int b,int c){v=a;idx=b;fa=c;}
};
nd prs(int p,int fa)//前驱
{if(tree[p].r)return prs(tree[p].r,p);return nd(tree[p].v,p,fa);
}
int suc(int p)//后继
{if(tree[p].l)return suc(tree[p].l);return tree[p].v;
}
void ist(int p,int tmp)
{if(p==0){p=root=++tot;tree[p].nw(tmp);return ;}if(tmp==tree[p].v)tree[p].vnum++;if(tmp<tree[p].v){tree[p].lnum++;if(!tree[p].l){tree[p].l=++tot;tree[tot].nw(tmp);}elseist(tree[p].l,tmp);}if(tmp>tree[p].v){if(!tree[p].r){tree[p].r=++tot;tree[tot].nw(tmp);}elseist(tree[p].r,tmp);}
}
void ck(int p=1)
{int ls=tree[p].l,rs=tree[p].r;if(ls)ck(ls);cout<<tree[p].v<<" "<<tree[p].vnum<<"\n";if(rs)ck(rs);
}
int ck_lnum(int p,int tmp)
{if(tree[p].v>=tmp&&tree[tree[p].l].v<tmp)return tree[p].lnum;if(tree[p].v>=tmp)return ck_lnum(tree[p].l,tmp);return ck_lnum(tree[p].r,tmp)+1;
}
int dt(int p)//结点p删除 , 返回新结点下标
{int ls=tree[p].l,rs=tree[p].r;if((!ls)&&(!rs))return 0;if((!ls)||(!rs))return ls|rs;nd ps=prs(tree[p].l,p);if(tree[ps.fa].l==ps.idx)tree[ps.fa].l=0;elsetree[ps.fa].r=0;return ps.idx;
}
void dlt(int p,int tmp)
{int ls=tree[p].l,rs=tree[p].r;if(tree[p].v==tmp)//删到根了 {tree[p].vnum--;if(!tree[p].vnum)root=dt(p);}else if(tmp<tree[p].v){tree[p].lnum--;if(tmp==tree[ls].v)tree[ls].vnum--;if(!tree[ls].vnum)//删除结点 {int tp=dt(ls);tree[tp].l=tree[ls].l;tree[tp].r=tree[ls].r;tree[p].l=tp;}elsedlt(ls,tmp);}else{if(tmp==tree[rs].v)tree[rs].vnum--;if(!tree[rs].vnum)//删除结点 {int tp=dt(rs);tree[tp].l=tree[rs].l;tree[tp].r=tree[rs].r;tree[p].r=tp;}elsedlt(rs,tmp);}ls=tree[p].l;rs=tree[p].r;
}
int get_prs(int p,int tmp)
{if(p==0)return -(int)1e9;if(tree[p].v<tmp)return max(tree[p].v,get_prs(tree[p].r,tmp));elsereturn get_prs(tree[p].l,tmp);
}
int get_suc(int p,int tmp)
{if(p==0)return (int)1e9;if(tree[p].v>tmp)return min(tree[p].v,get_suc(tree[p].l,tmp));elsereturn get_suc(tree[p].r,tmp);
}
int ck_top(int p,int tmp)
{if(tree[p].lnum+1==tmp)return tree[p].v;else if(tree[p].lnum+1>tmp)return ck_top(tree[p].r,tree[p].lnum+1-tmp);elsereturn ck_top(tree[p].l,tmp);
}
int main()
{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);//freopen("t.in","r",stdin);int m;cin>>m;while(m--){int op,x;cin>>op>>x;if(op==1)ist(root,x);if(op==2)dlt(root,x);if(op==3)cout<<ck_lnum(root,x)+1<<'\n';if(op==4)cout<<ck_top(root,x)<<'\n';if(op==5)cout<<get_prs(root,x)<<'\n'; if(op==6)cout<<get_suc(root,x)<<'\n';}}