#include <bits/stdc++.h>
using namespace std;
const int INF = 0x7fffffff;
#define int long long
int cst=1;
struct node{
int val,siz,cnt,ls,rs;
}tree[1000010];
void add(int x,int b)
{
tree[x].siz++;
if(tree[x].val==b) {tree[x].cnt++;return;}
if(tree[x].val>b) {
if(tree[x].ls==0) {
cst++;
tree[cst].siz=tree[cst].cnt=1;//存储节点
tree[cst].val=b;tree[x].ls=cst;
}else add(tree[x].ls,b);
}else {
if(tree[x].rs==0) {
cst++;
tree[cst].siz=tree[cst].cnt=1;
tree[cst].val=b;tree[x].rs=cst;
}else add(tree[x].rs,b);
}
}
int queryrank(int x,int b)//x的排名
{
if(x==0) return 0;
if(tree[x].val==b) return tree[tree[x].ls].siz;
else if(tree[x].val>b) return queryrank(tree[x].ls,b);
else return queryrank(tree[x].rs,b)+tree[x].cnt+tree[tree[x].ls].siz;//前尘与往世
}
int queryrknm(int x,int b)//排名为b的数
{
if(tree[tree[x].ls].siz>=b) return queryrknm(tree[x].ls,b);
if(tree[tree[x].ls].siz+tree[x].cnt>=b) return tree[x].val;
else return queryrknm(tree[x].rs,b-tree[tree[x].ls].siz-tree[x].cnt);
}
int queryprev(int x,int b,int ans)
{
if(tree[x].val>=b) {
if(tree[x].ls==0) return ans;
else return queryprev(tree[x].ls,b,ans);
}
else {
if(tree[x].rs==0) return tree[x].val;
else return queryprev(tree[x].rs,b,tree[x].val);
}
}
int querynext(int x,int b,int ans)
{
if(tree[x].val<=b) {
if(tree[x].rs==0) return ans;
else return querynext(tree[x].rs,b,ans);
}else {
if(tree[x].ls==0) return tree[x].val;
else return querynext(tree[x].ls,b,tree[x].val);
}
}
signed main()
{
int n,a,b;cin >> n;
for(int i = 1 ; i <= n ; i++) {
cin >> a >> b;
if(a==1) cout << queryrank(1,b)+1 << endl;
else if(a==2) cout << queryrknm(1,b) << endl;
else if(a==3) cout << queryprev(1,b,-INF) << endl;
else if(a==4) cout << querynext(1,b,INF) << endl;
else {
if(tree[1].cnt==0) {
tree[1].cnt=tree[1].siz=1;
tree[1].val=b;
}
else add(1,b);
}
}
}