This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
import sys | |
n = int(input()) | |
queue = [] | |
for i in range(n): | |
a = int(sys.stdin.readline().rstrip()) | |
if a > 0: | |
heapq.heappush(queue, -a) | |
elif a == 0: | |
if not queue: | |
print(0) | |
continue | |
print(-heapq.heappop(queue)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
import sys | |
n = int(input()) | |
queue = [] | |
for i in range(n): | |
a = int(sys.stdin.readline().rstrip()) | |
if a == 0: | |
if not queue: | |
print(0) | |
continue | |
print(heapq.heappop(queue)[1]) | |
else: | |
heapq.heappush(queue, (abs(a), a)) |
파이썬 내장모듈 heapq는 기본적으로 최소힙을 제공한다. 즉 queue에 원소들은 push한 후 pop을 했을 때 작은 값부터 나온다는 뜻이다. 해당 문제는 자연수 기준이므로 숫자를 음수로 바꾼 뒤 push하고, pop한 후 다시 -를 붙여주면 큰 수부터 출력할 수 있게 된다.
절댓값 힙은 절댓값과 본값을 가지는 튜플로 heapq를 수행한다. 튜플은 첫번째 원소를 기준으로 정렬되므로 절댓값으로 정렬 후 출력은 두번째 원소를 해주면 된다.
'코딩테스트 준비' 카테고리의 다른 글
백준 알고스팟 - 우선순위 큐, 너비우선탐색 (0) | 2021.03.21 |
---|---|
백준 - 유기농 배추 - bfs (0) | 2021.03.19 |
백준 최대 힙, 절댓값 힙 - heapq 사용, 파이썬 (0) | 2021.03.13 |
파이썬 itertools permutations! (0) | 2021.03.04 |
최소 신장(스패닝) 트리 - 크루스 칼 알고리즘!! (0) | 2021.02.27 |