import heapq
from collections import Counter
n=int(input())
s=[]
ms=[]
count=Counter()
for i in range(n):
    op=list(map(int,input().split()))
    if op[0]==1:
        if count[op[1]]==0:
            heapq.heappush(s,op[1])
            heapq.heappush(ms,-op[1]) 
        count[op[1]]+=1   
    if op[0]==2:
        while s and count[s[0]]==0:
            heapq.heappop(s)
        print(s[0])
    if op[0]==3:
        while ms and count[-ms[0]]==0:
            heapq.heappop(ms)
        print(-ms[0])
    if op[0]==4:
        while s and count[s[0]]==0:
            heapq.heappop(s)
        count[s[0]]-=1    
    if op[0]==5:
        while s and count[-ms[0]]==0:
            heapq.heappop(ms)
        count[-ms[0]]-=1