1927(최소힙) - 자료구조(python)

지환·2023년 10월 17일
0

백준(python)

목록 보기
60/67
post-thumbnail

출처 | https://www.acmicpc.net/problem/1927

코드

import sys 
import heapq

input = sys.stdin.readline
n = int(input())
queue = []
for _ in range(n):
  num = int(input())
  if num != 0: # 0을 입력하지 않았을 때
    heapq.heappush(queue,num)
  
  else:
    
    try:
      print(heapq.heappop(queue))

    except:
      print(0)      

코드 분석

try .. except를 실행한 이유는 heapq.heappop(queue)를 실행하는 부분에서 예외가 발생할 수 있는 상황을 처리하기 위해서다.

heapq.heappop은 힙(Heap)에서 가장 작은 원소를 삭제하고 반환하는 메서드다. 비어 있는 힙에서 heappop을 호출하면 IndexError 예외가 발생한다.

profile
아는만큼보인다.

0개의 댓글