알고리즘/baekjoon

[알고리즘/baekjoon] 1927_최소 힙(python)

천뿌니 2021. 11. 25. 13:02
728x90

문제

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

 

1927번: 최소 힙

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

www.acmicpc.net

# 최대힙 문제를 풀고오면 쉽게 풀 수 있다
# pypy3로 제출
 
정답
import heapq

n = int(input())
n_list = []
for _ in range(n):
  n_list.append(int(input()))

heap = []
heapq.heapify(heap)
for i in n_list:
  if i == 0 and len(heap) == 0:
    print(0)
  elif i == 0:
    print(heapq.heappop(heap))
  else:
    heapq.heappush(heap, i) # 최대 힙에서는 push할 때 -i지만 최소 힙은 i를 push 해준다.

 

* 깃허브를 참조해주세요!!

https://github.com/JunSeokCheon

 

JunSeokCheon - Overview

JunSeokCheon has 6 repositories available. Follow their code on GitHub.

github.com