#include<bits/stdc++.h>
using namespace std;
#define fi first
#define sc second
#define pii pair<int,int>
#define pb push_back
#define umap unordered_map
#define mset multiset
#define pq priority_queue
#define ull unsigned long long
#define i128 __int128
const int maxn=2e6+10;
int n,m;
struct Splay{
int rt=0,tot,f[maxn],ch[maxn][2],sz[maxn],cnt[maxn],val[maxn];
void pushup(int u){
sz[u]=cnt[u]+sz[ch[u][0]]+sz[ch[u][1]];
}
void clear(int x){
f[x]=ch[x][0]=ch[x][1]=sz[x]=cnt[x]=val[x]=0;
}
int get(int x){
return (ch[f[x]][1]==x);
}
void rot(int x){
int y=f[x],z=f[y],c=get(x);
ch[y][c]=ch[x][c^1];
if(ch[x][c^1]) f[ch[x][c^1]]=y;
ch[x][c^1]=y,f[y]=x,f[x]=z;
if(z) ch[z][y==ch[z][1]]=x;
pushup(y),pushup(x);
}
void splay(int x){
for(int fa=f[x];fa=f[x],fa;rot(x)){
if(f[fa]) rot(get(x)==get(fa)?fa:x);
}rt=x;
}
void insert(int x){
if(!rt) return val[++tot]=x,cnt[tot]++,rt=tot,pushup(rt),void();
int now=rt,fa=0;
while(1){
if(val[now]==x){
cnt[now]++,pushup(now),pushup(f[now]);
return splay(now),void();
}
fa=now,now=ch[now][val[now]<x];
if(!now){
val[++tot]=x,cnt[tot]++,f[tot]=fa,ch[fa][val[fa]<x]=tot;
pushup(tot),pushup(fa),splay(tot);
break;
}
}
}
int rnk(int x){
int res=0,now=rt;
while(1){
if(x<val[now]) now=ch[now][0];
else{
res+=sz[ch[now][0]];
if(!now) return res+1;
if(x==val[now]) return splay(now),res+1;
res+=cnt[now],now=ch[now][0];
}
}
}
int kth(int k){
int now=rt;
while(1){
if(ch[now][0]&&sz[ch[now][0]]>=k) now=ch[now][0];
else{
k-=cnt[now]+sz[ch[now][0]];
if(k<=0) return splay(now),val[now];
now=ch[now][1];
}
}
}
int pre(int x){
return kth(rnk(x)-1);
}
int nxt(int x){
return kth(rnk(x)+1);
}
void del(int x){
rnk(x);
if(cnt[rt]>1) return cnt[rt]--,pushup(rt),void();
if(!ch[rt][0]&&!ch[rt][1]) return clear(rt),rt=0,void();
if(!ch[rt][0]){
int now=rt;
rt=ch[rt][1],f[rt]=0;
return clear(now),void();
}
if(!ch[rt][1]){
int now=rt;
rt=ch[rt][0],f[rt]=0;
return clear(now),void();
}
int now=rt,u=ch[rt][0];
while(ch[u][1]) u=ch[u][1];
splay(u),f[ch[now][1]]=u;
ch[u][1]=ch[now][1],clear(now);
pushup(rt);
}
}tr;
void solve(){
cin>>n;
while(n--){
int op,x;
cin>>op>>x;
if(op==1) tr.insert(x);
if(op==2) tr.del(x);
if(op==3) tr.insert(x),cout<<tr.rnk(x)<<endl,tr.del(x);
if(op==4) cout<<tr.kth(x)<<endl;
if(op==5) tr.insert(x),cout<<tr.pre(x)<<endl,tr.del(x);
if(op==6) tr.insert(x),cout<<tr.nxt(x)<<endl,tr.del(x);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t=1;
while(t--) solve();
return 0;
}