#include<bits/stdc++.h>
using namespace std;
#define N 10000010
int cnt,n,root;
struct treap
{
int cnt,size,v,rd,ch[2];
}t[N];
void update(int x){t[x].size=t[t[x].ch[0]].size+t[t[x].ch[1]].size+t[x].cnt;}
void rotate(int x,int d)
{
int son=t[x].ch[d];
t[x].ch[d]=t[son].ch[d^1];
t[son].ch[d^1]=x;
update(x);
update(x=son);
}
void insert(int &x,int val)
{
if(!x)
{
x=++cnt;
t[x].cnt=t[x].size=1;
t[x].v=val,t[x].rd=rand();
}
t[x].size++;
if(t[x].v==val){t[x].cnt++;return;}
int d=t[x].v<val;
insert(t[x].ch[d],val);
if(t[x].rd>t[t[x].ch[d]].rd) rotate(x,d);
}
void Delete(int &x,int val)
{
if(!x) return;
if(t[x].v==val)
{
if(t[x].cnt>1){t[x].cnt--;t[x].size--;return;}
bool d=t[t[x].ch[0]].rd<t[t[x].ch[1]].rd;
if(t[x].ch[0]==0||t[x].ch[1]==0) x=t[x].ch[0]+t[x].ch[1];
else rotate(x,d),Delete(t[x].ch[d^1],val);
}
else t[x].size--,Delete(t[x].ch[t[x].v<val],val);
update(x);
}
int dk(int root,int val)
{
int x=root;
while(1)
{
if(val<=t[t[x].ch[0]].size) x=t[x].ch[0];
else if(val>t[t[x].ch[0]].size+t[x].size){val-=t[t[x].ch[0]].size+t[x].size;x=t[x].ch[1];}
else return t[x].v;
}
}
int pre(int x,int val)
{
if(!x) return -999999999;
if(t[x].v>=val) return pre(t[x].ch[0],val);
else return max(pre(t[x].ch[1],val),t[x].v);
}
int nex(int x,int val)
{
if(!x) return 999999999;
if(t[x].v<=val) return nex(t[x].ch[1],val);
else return min(nex(t[x].ch[0],val),t[x].v);
}
int get_z(int x,int val)
{
if(!x) return 0;
if(t[x].v==val) return t[t[x].ch[0]].size+1;
if(t[x].v>val) return get_z(t[x].ch[0],val);
return get_z(t[x].ch[1],val)+t[t[x].ch[0]].size+t[x].cnt;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
int opt,x;
cin>>opt>>x;
if(opt==1) insert(root,x);
if(opt==2) Delete(root,x);
if(opt==3) cout<<get_z(root,x)-1<<endl;
if(opt==4) cout<<dk(root,x)<<endl;
if(opt==5) cout<<pre(root,x)<<endl;
if(opt==6) cout<<nex(root,x)<<endl;
}
return 0;
}