Pagini recente » Cod sursa (job #41992) | Cod sursa (job #459359) | Cod sursa (job #2209721) | Cod sursa (job #2049700) | Cod sursa (job #2449241)
#!/usr/bin/env python3
import sys
sys.stdout = open('heapuri.out', 'w')
with open('heapuri.in', 'r') as f:
readInts = lambda: map(int, f.readline().split())
h, pos = [-1], [-1]
def up(idx):
x = h[idx]
while idx > 1 and x < h[idx // 2]:
h[idx] = h[idx // 2]
pos[h[idx][1]] = idx
idx //= 2
h[idx] = x
pos[x[1]] = idx
def insert(val):
h.append((val, len(pos)))
pos.append(len(h) - 1)
idx = pos[-1]
up(idx)
def remove(i):
idx = pos[i]
h[idx] = -1, i
up(idx)
idx = pos[i]
popped = h.pop()
if popped[1] == i: return
h[idx] = popped
pos[h[idx][1]] = idx
while True:
minIdx = idx
if idx * 2 < len(h) and h[idx] > h[idx * 2]: minIdx = idx * 2
if idx * 2 + 1 < len(h) and h[minIdx] > h[idx * 2 + 1]: minIdx = idx * 2 + 1
if minIdx == idx: break
h[idx], h[minIdx] = h[minIdx], h[idx]
pos[h[idx][1]] = idx
pos[h[minIdx][1]] = minIdx
idx = minIdx
for _ in range(next(readInts())):
op = tuple(readInts())
if op[0] == 1: insert(op[1])
elif op[0] == 2: remove(op[1])
elif op[0] == 3: print(h[1][0])