Max heap implementation

whitehousechef·2023년 10월 28일
0

I was solving https://www.acmicpc.net/problem/11279
when I encountered max heap.

When we heapify our heap, unlike a min heap, we have to negate the value when we push or pop from our max heap.

import heapq
import sys
input = sys.stdin.readline

n = int(input())
heap = []
heapq.heapify(heap)
for _ in range(n):
    m = int(input())
    if m==0:
        if not heap:
            print(0)
        else:
            print(-heapq.heappop(heap))
    else:
        heapq.heappush(heap,-m)

0개의 댓글