백준 11279 - 최대 힙 (파이썬)

Updated:

Answer

import sys

def insert(heap, num):
    heap.append(num)
    i = len(heap) - 1

    while i > 1:
        if heap[i] > heap[i // 2]:
            heap[i], heap[i // 2] = heap[i // 2], heap[i]
            i //= 2
        else:
            break

def remove(heap):
    max_val = heap[1]
    tmp = heap.pop()

    parent = 1
    child = 2
    heap_len = len(heap)

    while child <= heap_len - 1:
        if child < heap_len - 1 and heap[child] < heap[child + 1]:
            child += 1

        print(child, child // 2, heap)
        if heap[child] <= tmp:
            break

        heap[parent] = heap[child]

        parent = child
        child *= 2

    if heap_len != 1:
        heap[parent] = tmp

    return max_val

n = int(sys.stdin.readline())
heap = [0]

for _ in range(n):
    num = int(sys.stdin.readline())

    if num == 0:
        if len(heap) == 1:
            print(0)
        else:
            print(remove(heap))
    else:
        insert(heap, num)

Categories:

Updated: