한 걸음씩

[백준][python] 1927 최소 힙 ✅ 본문

BOJ

[백준][python] 1927 최소 힙 ✅

winter17 2023. 1. 27. 23:20

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

 

1927번: 최소 힙

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

www.acmicpc.net

풀이 과정

1. 입력 값이 0이 아닐 때 heapq.heappush 하고

2. 0일 때 heap이라면 pop 하고 출력

3. heap이 아니라면 0 출력

import heapq # 최소 힙의 형태로 정렬
heap = []
# 순회하면서 찾아야함
for _ in range(int(input())):  # 의미 없는 순회는 _ 이렇게 표시함
    n = int(input())
    # 0이 아니면 heappush
    if n != 0:
        heapq.heappush(heap, n)
    # 0이면 heappop
    else:
        if heap:  # if len(heap) != 0
            print(heapq.heappop(heap))  # 가장 작은 원소 출력
        else:
            print(0)

https://docs.python.org/ko/3/library/heapq.html?highlight=heapq 

 

heapq — Heap queue algorithm

Source code: Lib/heapq.py This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Heaps are binary trees for which every parent node has a va...

docs.python.org


리뷰

수업 시간에 리뷰 한번 하고 저녁에 다시 풀어보는데 또 못 풀었다

힙큐 자료구조를 처음 보고 바로 문제에 적용하려니까 쉽지 않아...,,, 알 것 같은데 잘 모르겠고!!

뭔가 아직 완벽하게 이해된 것 같진 않다

내일 다시 풀어봐야지