#!/usr/bin/python3 # A priority queue # # a program that reads insertions and extractions from the input: # + calls enqueue(element, priority) # - calls dequeue() Q = [] # array of *pairs* (e,p) def parent(x): # Warning: not exactly the same as in pseudo-code # where positions start from 1 return (x - 1)//2 def left(x): return 2*x + 1 def right(x): return 2*x + 2 def enqueue(Q, e, p): Q.append((e,p)) i = len(Q) - 1 while i > 0 and Q[i][1] > Q[parent(i)][1]: # swap Q[i] <--> Q[parent(i)] tmp = Q[i] Q[i] = Q[parent(i)] Q[parent(i)] = tmp i = parent(i) def dequeue(Q): if len(Q) == 0: return None # swap root with the last element result = Q[0] Q[0] = Q[len(Q) - 1] del Q[len(Q) - 1] # run max-heapify i = 0 # pos of the max element -- max among i, left(i), right(i) m = 0 while True: if left(i) < len(Q): if Q[m][1] < Q[left(i)][1]: m = left(i) if right(i) < len(Q) and Q[m][1] < Q[right(i)][1]: m = right(i) if m != i: tmp = Q[i] Q[i] = Q[m] Q[m] = tmp i = m else: break return result import sys for l in sys.stdin: # line-by-line iteration l = l.split() if len(l) == 0: # skip empty lines continue if l[0] == '+': enqueue(Q, l[1], int(l[2])) elif l[0] == '-': print(dequeue(Q)) elif l[0] == '?': print(Q) else: print('unknown command', l[0])