Cod sursa(job #2449231)

Utilizator voyagerSachelarie Bogdan voyager Data 18 august 2019 21:59:47
Problema Heapuri Scor 40
Compilator py Status done
Runda Arhiva educationala Marime 1.28 kb
#!/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 insert(val):
        h.append((val, len(pos)))
        pos.append(len(h) - 1)

        idx = len(h) - 1
        while idx > 1 and val < h[idx // 2][0]:
            h[idx] = h[idx // 2]
            pos[h[idx][1]] = idx
            idx = idx // 2
        h[idx] = val, len(pos) - 1
        pos[-1] = idx

    def remove(i):
        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])