[알고리즘] 백준 11286 : 절댓값 힙 - S1

eternal moment·2023년 5월 1일
0

2023.05.01 풀이

import sys
input=sys.stdin.readline
import heapq

n=int(input())
arr=[]

for _ in range(n):
    x=int(input())
    if x==0:
        if len(arr)==0:
            print(0)
        else:
            print(heapq.heappop(arr)[1])
    else:
        heapq.heappush(arr, (abs(x), x))
  • heap을 tuple로 구성했을 때 맨 앞 숫자만 가지고 정렬하므로 앞은 abs(절대값) 내장 함수를 써주고 두 번째는 원래 수를 써줌으로써 절댓값 정렬을 할 수 있게 한다.

다른 풀이

import heapq
import sys
input = sys.stdin.readline
hq = []

for i in range(int(input())):
    a = int(input())
    if a :
        heapq.heappush(hq, (abs(a), a))
    else:
        print(heapq.heappop(hq)[1] if hq else 0)

check point

  • 힙을 튜플로 구성 시 앞 숫자로만 정렬함

0개의 댓글