#include <bits/stdc++.h>
#define F(i, j, k) for(int i=(j), END=(k); i<=END; ++i)
#define R(i, j, k) for(int i=(j), END=(k); i>=END; --i)
#define debug(x) cout<<#x<<' '<<x<<'\n'
#define de(x) cout<<#x<<' '<<x<<" "
using namespace std;
const int N=1e5+7, INF=1e9;
int rt, tot, cnt[N], s[N], val[N], dat[N], son[N][2];
mt19937 rng(time(0));
void push_up(int p){
s[p]=s[son[p][0]]+s[son[p][1]]+cnt[p];
}
void rotate(int &p, int d){
int k=son[p][d^1];
son[p][d^1]=son[k][d];
son[k][d]=p;
push_up(p), push_up(k);
p=k;
}
void ins(int &p, int x){
if(!p){
p=++tot;
cnt[p]=s[p]=1, dat[p]=rng()%INF, val[p]=x;
return;
}
if(val[p]==x) ++cnt[p], ++s[p];
else{
int d=(x>val[p]);
ins(son[p][d], x);
push_up(p);
if(dat[p]<dat[son[p][d]]) rotate(p, d^1);
}
}
void del(int &p, int x){
if(!p) return;
if(val[p]==x){
if(cnt[p]>1){
--cnt[p], --s[p];
return;
}
if(son[p][0] || son[p][1]){
if(!son[p][1] || dat[son[p][0]]>dat[son[p][1]])
rotate(p, 1), del(son[p][1], x);
else
rotate(p, 0), del(son[p][0], x);
push_up(p);
} else p=0;
return;
}
del(son[p][x>val[p]], x);
}
int rk(int p, int x){
if(!p) return 0;
if(val[p]==x) return s[son[p][0]];
if(val[p]<x) return cnt[p]+s[son[p][0]]+rk(son[p][1], x);
return rk(son[p][0], x);
}
int find(int p, int x){
if(!p) return INF;
if(x<=s[son[p][0]]) return find(son[p][0], x);
if(x<=s[son[p][0]]+cnt[p]) return val[p];
return find(son[p][1], x-cnt[p]-s[son[p][0]]);
}
int pre(int p, int x){
int res=-INF;
while(p)
if(val[p]>=x) p=son[p][0];
else res=max(p, val[p]), p=son[p][1];
return res;
}
int nxt(int p, int x){
int res=INF;
while(p)
if(val[p]<=x) p=son[p][1];
else res=min(res, val[p]), p=son[p][0];
return res;
}
void print(int p){
if(!p) return;
de(val[p]), de(cnt[p]), de(s[p]), de(son[p][0]), debug(son[p][1]);
print(son[p][0]), print(son[p][1]);
}
signed main()
{
freopen("1.out", "w", stdout);
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
srand(time(0));
int T; cin>>T;
while(T--){
int opt, x;
cin>>opt>>x;
if(opt==1) ins(rt, x);
else if(opt==2) del(rt, x);
else if(opt==3) cout<<rk(rt, x)+1<<'\n';
else if(opt==4) cout<<find(rt, x)<<'\n';
else if(opt==5) cout<<pre(rt, x)<<'\n';
else cout<<nxt(rt, x)<<'\n';
}
return 0;
}