알고리즘 | 백준 11286

이도운·2022년 2월 9일
0

TIL

목록 보기
69/73
post-thumbnail

문제

절댓값 힙은 다음과 같은 연산을 지원하는 자료구조이다.

  • 배열에 정수 x (x ≠ 0)를 넣는다.
  • 배열에서 절댓값이 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다. 절댓값이 가장 작은 값이 여러개일 때는, 가장 작은 수를 출력하고, 그 값을 배열에서 제거한다.

프로그램은 처음에 비어있는 배열에서 시작하게 된다.

풀이

import heapq as hq
import sys

input = sys.stdin.readline
min_heap = []
max_heap = []
for _ in range(int(input())):
    x = int(input())
    if x:
        if x > 0:
            hq.heappush(min_heap, x)
        else:
            hq.heappush(max_heap, -x)
    else:
        if min_heap:
            if max_heap:
                if min_heap[0] < abs(-max_heap[0]):
                    print(hq.heappop(min_heap))
                else:
                    print(-hq.heappop(max_heap))
            else:
                print(hq.heappop(min_heap))
        else:
            if max_heap:
                print(-hq.heappop(max_heap))
            else:
                print(0)
profile
⌨️ 백엔드개발자 (컴퓨터공학과 졸업)

0개의 댓글