(python)백준-카드 정렬하기

DongDong·2023년 9월 11일
0

알고리즘 문제풀이

목록 보기
11/20

문제

가장 작은 카드 묶음끼리 먼저 합칠때가 최소의 비교를 할 때이다.
heapq 우선순위 큐를 사용하여 가장작은 카드 묶음 두개를 꺼내서 합친 후 다시 큐에 넣는 과정을 큐안에 원소가 1개 남아있을 때까지 반복하면 된다.

import sys
import heapq

n=int(sys.stdin.readline())
array=[]

for i in range(n):
    data=int(sys.stdin.readline())
    heapq.heappush(array,data)

result=0
while len(array)!=1:
    a=heapq.heappop(array)
    b=heapq.heappop(array)

    result+=a+b

    heapq.heappush(array,(a+b))

print(result)

0개의 댓글