[백준/파이썬] 1927번: 최소 힙

수박강아지·2025년 1월 13일

BAEKJOON

목록 보기
19/174

문제

https://www.acmicpc.net/problem/1927

풀이

heapq 모듈을 사용하면 쉽게 풀 수 있다.

  • heapq.heappush(heap, item) : heap에 item 추가
  • heapq.heappop(heap) : heap에서 가장 작은 원소 pop & return, 비어있는 경우 IndexError 발생
  • heapq.heapify(arr) : 리스트 arr을 heap으로 변환

코드

import sys, heapq
input = sys.stdin.readline

heap = []
for i in range(int(input())):
    n = int(input())
    if n != 0:
        heapq.heappush(heap, n)
    else:
        try:
            print(heapq.heappop(heap))
        except:
            print(0)

0개의 댓글