Algorithm/백준

항해99 리부트코스 알고리즘 2주 2일차 백준 1927 최소 힙

Albosa2lol 2024. 7. 25. 17:03

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

 

 

 

 

import sys  
import heapq 

input = sys.stdin.readline

def main():
    n = int(input().strip()) 
    min_heap = []  # 빈 리스트를 최소 힙으로 사용

    for _ in range(n):
        x = int(input().strip())  # 각 명령을 입력받음
        if x == 0:
            if min_heap:
                # 힙이 비어있지 않으면 최소 값을 출력하고 힙에서 제거
                print(heapq.heappop(min_heap))
            else:
                # 힙이 비어있으면 0을 출력
                print(0)
        else:
            # x가 0이 아니면 힙에 값을 추가
            heapq.heappush(min_heap, x)

if __name__ == "__main__":
    main()

 

 

  • 최소 힙을 구현하기 위해 파이썬의 heapq 모듈을 사용
  • 입력을 읽고 각 명령을 처리
  • 힙에 숫자를 추가하고, 0일 경우 최소 값을 출력하고 힙에서 제거