#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define mian main
using namespace std;
struct Node{
int r, val, name;
Node* ch[2];
int cmp(int x) const{
if(x == val) return -1;
return x < val ? 0 : 1;
}
};
void rotate(Node*& o, int d){ // d=0左旋,d=1右旋
Node* k = o->ch[d^1];
o->ch[d^1] = k->ch[d];
k->ch[d] = o;
o = k;
}
void insert(Node*& o, int name, int val){
if(o == NULL){
o = new Node();
o->ch[0] = o->ch[1] = NULL;
o->val = val;
o->name = name;
o->r = rand();
}
else{
int d = o->cmp(val);
insert(o->ch[d], name, val);
if(o->ch[d]->r > o->r)
rotate(o, d^1);
}
}
void remove(Node*& o, int x){
int d = o->cmp(x);
if(d == -1){
if(o->ch[0] == NULL)
o = o->ch[1];
else
if(o->ch[1] == NULL)
o = o->ch[0];
else{
int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
rotate(o, d2);
remove(o->ch[d2], x);
}
}
else
remove(o->ch[d], x);
}
int find_max(Node* o, int& name){
if(o == NULL)
return -1;
while(o->ch[1] != NULL)
o = o->ch[1];
name = o->name;
return o->val;
}
int find_min(Node* o, int& name){
if(o == NULL)
return -1;
while(o->ch[0] != NULL)
o = o->ch[0];
name = o->name;
return o->val;
}
int main(){
//freopen("ztest.txt","r",stdin);
int n;
Node* root = NULL;
while(scanf("%d", &n) && n){
if(n == 2)
{
int name;
int maxv = find_max(root, name);
if(maxv == -1)
printf("0\n");
else{
printf("%d\n",name);
remove(root, maxv);
}
}
if(n == 3)
{
int name;
int minv = find_min(root, name);
if(minv == -1)
printf("0\n");
else{
printf("%d\n",name);
remove(root, minv);
}
}
if(n == 1)
{
int name, val;
scanf("%d%d", &name, &val);
insert(root, name, val);
}
}
return 0;
}