BOJ 11279. 최대 힙 (Python)

2021. 2. 23. 01:43Problem Solving/BOJ

BOJ 11279. 최대 힙

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

 

11279번: 최대 힙

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

www.acmicpc.net

풀이

heapq를 이용해서 풀었다. 주의할 점 세가지는,

  1. python3로 제출할 경우 시간초과, pypy3로 제출
  2. input()으로 할 시 시간초과, sys.stdin.readline().rstrip()로 할 것
  3. 최대 힙으로 만들기 위해 (-n, n)로 튜플을 넘겨주어 -n기준 최소 힙 생성. heapq.heappop(heap)[1] 하여 n기준 최대 힙이 된다.

소스코드

import heapq
from sys import stdin

N = int(stdin.readline().rstrip())
heap = []

for _ in range(N):
    command = int(stdin.readline().rstrip())

    if command == 0:
        if len(heap) == 0:
            print(0)
        else:
            print(heapq.heappop(heap)[1])
    else:
        heapq.heappush(heap, (-command, command))

반응형

'Problem Solving > BOJ' 카테고리의 다른 글

BOJ 4153. 직각삼각형 (C)  (0) 2021.03.07
BOJ 1927. 최소 힙 (Python)  (0) 2021.02.23
BOJ 2606. 바이러스 (Python)  (0) 2021.02.22
BOJ 1003. 피보나치 함수 (Python)  (0) 2021.02.19
BOJ 1764. 듣보잡 (Python)  (0) 2021.02.19