#include <iostream>
using namespace std;
const int N=5e4+10,inf=2147483647;
int cnt;
struct node{
int value,ls,rs,siz,c;
node(){value=0,ls=-1,rs=-1,siz=0,c=0;}
} tree[N];
int n,ans;
void push_up(int p){
tree[p].siz=tree[tree[p].ls].siz+tree[tree[p].rs].siz+tree[p].c;
}
void update(int x,int p){
if(!cnt){
cnt++;
tree[cnt].value=x;
tree[cnt].ls=tree[cnt].rs=-1;
tree[cnt].c=tree[cnt].siz=1;
return;
}
else if(x<tree[p].value){
if(tree[p].ls!=-1) update(x,tree[p].ls);
cnt++;
tree[cnt].value=x;
tree[cnt].ls=tree[cnt].rs=-1;
tree[cnt].c=tree[cnt].siz=1;
tree[p].ls=cnt;
}
else if(x==tree[p].value) tree[p].c++,cnt++;
else{
if(tree[p].rs!=-1) update(x,tree[p].rs);
cnt++;
tree[cnt].value=x;
tree[cnt].ls=tree[cnt].rs=-1;
tree[cnt].c=tree[cnt].siz=1;
tree[p].rs=cnt;
}
push_up(p);
}
int query_kth1(int x,int p){
if(p==-1) return 0;
if(x==tree[p].value) return tree[tree[p].ls].siz+1;
else if(x<tree[p].value) return query_kth1(x,tree[p].ls);
else if(x>tree[p].value) return query_kth1(x,tree[p].rs)+tree[tree[p].ls].siz+1;
return 0;
}
int query_kth2(int x,int p){
if(p==-1) return 0;
if(x==tree[tree[p].ls].siz+1) return tree[p].value;
if(x>tree[tree[p].ls].siz+1) return query_kth2(x-tree[tree[p].ls].siz-1,tree[p].rs);
if(x<tree[tree[p].ls].siz+1) return query_kth2(x,tree[p].ls);
return 0;
}
void query_pre(int x,int p){
if(p==-1) return;
if(x>tree[p].value){
ans=max(ans,tree[p].value);
query_pre(x,tree[p].rs);
}else if(x<=tree[p].value) query_pre(x,tree[p].ls);
return;
}
void query_nex(int x,int p){
if(p==-1) return;
if(x<tree[p].value){
ans=min(ans,tree[p].value);
query_nex(x,tree[p].ls);
}else if(x>=tree[p].value) query_nex(x,tree[p].rs);
return;
}
void debug(int p){
cout<<"tree["<<p<<"].value="<<tree[p].value<< " ";
cout<<"tree["<<p<<"].size="<<tree[p].value<<" ";
cout<<"tree["<<p<<"].ls="<<tree[p].ls<<" ";
cout<<"tree["<<p<<"].rs="<<tree[p].rs<<" ";
cout<<"\n";
if(tree[p].ls!=-1) debug(tree[p].ls);
if(tree[p].rs!=-1) debug(tree[p].rs);
}
signed main(){
cin>>n;
for(int i=1;i<=n;i++){
int op,x;cin>>op>>x;
if(op==1) cout<<query_kth1(x,1)<<"\n";
else if(op==2) cout<<query_kth2(x,1)<<"\n";
else if(op==3) {
ans=-inf;
query_pre(x,1);
cout<<ans<<"\n";
}
else if(op==4) {
ans=inf;
query_nex(x,1);
cout<<ans<<"\n";
}
else update(x,1);
}
// debug(1);
return 0;
}
debug 函数会遍历整个树