✔ 풀이를 위한 아이디어
✔ 수정 전 코드 [시간 초과]
import sys
N = int(sys.stdin.readline())
Heap = [-1]
for _ in range(N):
x = int(sys.stdin.readline())
if x == 0:
if len(Heap) == 1:
print("0")
else:
Heap[1], Heap[len(Heap) - 1] = Heap[len(Heap) - 1], Heap[1]
print(Heap.pop())
i = 1
while True:
if 2*i < len(Heap)-1:
if Heap[i] < Heap[2*i]:
Heap[i], Heap[2*i] = Heap[2*i], Heap[i]
i = 2*i
elif 2*i+1 < len(Heap)-1:
if Heap[i] < Heap[2*i+1]:
Heap[i], Heap[2*i+1] = Heap[2*i+1], Heap[i]
i = 2*i+1
else:
break
else:
Heap.append(x)
i = len(Heap) - 1
while i > 1:
if Heap[i] > Heap[i//2]:
Heap[i], Heap[i//2] = Heap[i//2], Heap[i]
i = i//2
else:
break
✔ 수정 후 코드
import sys
import heapq
N = int(sys.stdin.readline())
Heap = []
for _ in range(N):
x = int(sys.stdin.readline())
if x == 0:
if len(Heap) == 0:
print("0")
else:
tmp = heapq.heappop(Heap)
print(tmp[1])
else:
heapq.heappush(Heap, (-x, x))
✔ 관련 개념