#include<bits/stdc++.h>
using namespace std;
struct node{
int size;
int rank;
int key;
int flag;
node *son[2];
bool operator < (const node &a)const{return rank<a.rank;}
node(){
son[0]=son[1]=NULL;
rank=rand();
key=0;
size=1;
flag=1;
}
int cmp(int x)const{
return x<=key?0:1;
}
void update(){
size=flag;
if(son[0]!=NULL)size+=son[0]->size;
if(son[1]!=NULL)size+=son[1]->size;
}
};
node* root;
void rotate(node* &o,int d){
node *k=o->son[d^1];
o->son[d^1]=k->son[d];
k->son[d]=o;
o->update();
k->update();
o=k;
}
void insert(node* &o,int x){
if(o==NULL){
o=new node();
o->key=x;
return;
}
else if(o->key==x){
o->flag++;
o->update();
return;
}
int d=x>o->key?1:0;
insert(o->son[d],x);
if(o<o->son[d]){
rotate(o,d^1);
}
else o->update();
}
void remove(node* &o,int x){
if(o==NULL)return;
if(o->key==x){
if(o->flag>1)o->flag--;
else{
if(o->son[0]==NULL&&o->son[1]==NULL){
o=NULL;
}
else if(o->son[0]!=NULL&&o->son[1]!=NULL){
if(o->son[0]>o->son[1]){
rotate(o,1),remove(o->son[1],x);
}
else rotate(o,0),remove(o->son[0],x);
}
else {
if(o->son[0]==NULL){
o=o->son[1];
}
else {
o=o->son[0];
}
}
}
if(o!=NULL) o->update();
}
else{
if(x<o->key)remove(o->son[0],x);
if(x>o->key)remove(o->son[1],x);
if(o!=NULL) o->update();
}
}
int kth(node* o,int k){
if(o==NULL||k<0||k>o->size){
return 0;
}
int s=o->son[0]!=NULL?o->son[0]->size:0;
if(k>=s+1&&k<=o->flag+s){
return o->key;
}
else if(k<=s){
return kth(o->son[0],k);
}
else{
return kth(o->son[1],k-s-o->flag);
}
}
int find(node *o,int k){
if(o==NULL)return 0;
int s=o->son[0]!=NULL?o->son[0]->size:0;
if(o->key==k){
return s+1;
}
if(o->key>k){
return find(o->son[0],k);
}
else {
return s+o->flag+find(o->son[1],k);
}
}
void front(node* o,int k,int &ans){
if(o==NULL)return;
if(o->key<k){
if(o->key>ans){
ans=o->key;
}
if(o->son[1]!=NULL){
front(o->son[1],k,ans);
}
}
else if(o->key>=k){
if(o->son[0]!=NULL){
front(o->son[0],k,ans);
}
}
}
void back(node* o,int k,int &ans){
if(o==NULL)return;
if(o->key>k){
if(o->key<ans){
ans=o->key;
}
if(o->son[0]!=NULL){
back(o->son[0],k,ans);
}
}
else if(o->key<=k){
if(o->son[1]!=NULL){
back(o->son[1],k,ans);
}
}
}
inline int read()
{
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
int t,a,b;
int main(){
srand(19620817);
t=read();
while(t--){
a=read();
b=read();
if(a==1){
insert(root,b);
}
else if(a==2){
remove(root,b);
}
else if(a==3){
int ans3=find(root,b);
printf("%d\n",ans3);
}
else if(a==4){
int ans4=kth(root,b);
printf("%d\n",ans4);
}
else if(a==5){
int ans5=-1e9;
front(root,b,ans5);
printf("%d\n",ans5);
}
else if(a==6){
int ans6=1e9;
back(root,b,ans6);
printf("%d\n",ans6);
}
}
return 0;
}