본문 바로가기

백준 문제 풀이 및 피드백

2023.01.18 최소힙 백준[파이썬]

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

 

1927번: 최소 힙

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

import sys
from heapq import heappop, heappush
input = sys.stdin.readline

heap = []

n = int(input().strip())

for i in range(n):
    a = int(input().strip())
    if a == 0:
        if heap:
            print(heappop(heap))
        else:
            print(0)
    else:
        heappush(heap,a)

최소 힙 문제이다 heapq 모듈을 사용해서 바로 풀었다.