#include<bits/stdc++.h>
using namespace std;
#define N 200010
int n,x,y,tot,root;
struct node{
int son[2];
int Size;
int val;
int cnt;
int Rank;
}t[N];
void update(int x){
t[x].Size=t[t[x].son[0]].Size+t[t[x].son[1]].Size+t[x].cnt;
}
void R(int &root,int k){
int tmp=t[root].son[!k];
t[root].son[!k]=t[tmp].son[k];
t[tmp].son[k]=root;
update(root);update(tmp);
root=tmp;
}
void insert(int &root,int k){
if(!root){
root=++tot;
t[root].Size=t[root].cnt=1;
t[root].val=k;
t[root].Rank=rand()*rand()%19620817;
return ;
}
if(t[root].val==k){
t[root].Size++;
t[root].cnt++;
return ;
}
int d=k>t[root].val;
insert(t[root].son[d],k);
if(t[root].Rank>t[t[root].son[d]].Rank)
R(root,!d);
update(root);
return ;
}
void del(int &root,int k){
if(!root)return ;
if(k==t[root].val){
if(t[root].cnt>=1){
t[root].cnt--;
t[root].Size--;
}
if(t[root].cnt==0){
if(!t[root].son[0]&&!t[root].son[1]){
t[root].cnt=t[root].Size=0;
root=0;
}
else if(!t[root].son[0]&&t[root].son[1]){
R(root,0);
del(t[root].son[0],k);
}
else if(t[root].son[0]&&!t[root].son[1]){
R(root,1);
del(t[root].son[1],k);
}
else{
int d=t[t[root].son[0]].Rank<t[t[root].son[1]].Rank;
R(root,d);
del(t[root].son[d],k);
}
}
}
else if(k>t[root].val)
del(t[root].son[1],k);
else if(k<t[root].val)
del(t[root].son[0],k);
update(root);
return ;
}
int Rank(int &root,int k){
if(!root)return 0;
if(k>t[root].val)
return t[t[root].son[0]].Size+1+Rank(t[root].son[1],k);
return Rank(t[root].son[0],k);
}
int kth_Rank(int &root,int k){
if(k==t[t[root].son[0]].Size+1)
return t[root].val;
if(k>t[t[root].son[0]].Size+1)
return kth_Rank(t[root].son[1],k-t[t[root].son[0]].Size-1);
return kth_Rank(t[root].son[0],k);
}
int pre(int k){
int now=root,ans;
while(now){
if(t[now].val<k){
ans=t[now].val;
now=t[now].son[1];
}
else
now=t[now].son[0];
}
return ans;
}
int nxt(int k){
int now=root,ans;
while(now){
if(t[now].val>k){
ans=t[now].val;
now=t[now].son[0];
}
else
now=t[now].son[1];
}
return ans;
}
int main() {
srand(clock());
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d%d",&x,&y);
if(x==1)insert(root,y);
if(x==2)del(root,y);
if(x==3)printf("%d\n",Rank(root,y)+1);
if(x==4)printf("%d\n",kth_Rank(root,y));
if(x==5)printf("%d\n",pre(y));
if(x==6)printf("%d\n",nxt(y));
}
return 0;
}