Hanbit the Developer

[그리디] Python - 15903번, 카드 합체 놀이 본문

Algorithm/백준

[그리디] Python - 15903번, 카드 합체 놀이

hanbikan 2021. 4. 2. 15:27

www.acmicpc.net/problem/15903

import heapq
import sys
input = sys.stdin.readline


def getMergedCards(cards):
    newCard = heapq.heappop(cards) + heapq.heappop(cards)
    heapq.heappush(cards, newCard)
    heapq.heappush(cards, newCard)
    return cards


n, m = map(int, input().split())
cards = list(map(int, input().split()))
heapq.heapify(cards)

for _ in range(m):
    cards = getMergedCards(cards)

print(sum(cards))

 

가장 작은 두 수를 계속해서 합체하면 된다. 이를 위해서 우선순위 큐를 사용하였다.

간결하여 코드 가독성이 좋으며 시간 복잡도도 88ms로, 1등(76ms)과 유사하다.