[백준] 1715. 카드 정렬하기

원숭2·2022년 1월 30일
0

백준

목록 보기
23/54

문제

풀이

  1. 합 연산 후 비교를 기존 카드 뭉치끼리 하는 것이 아니라, 카드 뭉치를 합친 것들과도 비교를 해야함.
  2. 두개의 카드뭉치를 heappop 후, 합을 한 결과를 다시 heappush 하여 더 이상 비교를 할 수 없을 때 까지 연산을 진행함.
  3. 카드 뭉치가 1개인 경우, 비교를 진행할 수 없으므로 0 return.

코드

import heapq
import sys

def card() :
    n = int(sys.stdin.readline())
    heap = []
    
    res = 0
    for _ in range(n) :
        heapq.heappush(heap, int(sys.stdin.readline()))
    
    if len(heap) == 1 :
        return 0
    else :
        res = []
        while len(heap) != 1 :
            a = heapq.heappop(heap)
            b = heapq.heappop(heap)
            tmp = a + b
            res.append(tmp)
            heapq.heappush(heap, tmp)
        return sum(res)
    
print(card())

0개의 댓글