문제
풀이
- 합 연산 후 비교를 기존 카드 뭉치끼리 하는 것이 아니라, 카드 뭉치를 합친 것들과도 비교를 해야함.
- 두개의 카드뭉치를 heappop 후, 합을 한 결과를 다시 heappush 하여 더 이상 비교를 할 수 없을 때 까지 연산을 진행함.
- 카드 뭉치가 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())