나의 개발일지

[백준] 1715 카드 정렬하기 [Python, 파이썬] 본문

백준

[백준] 1715 카드 정렬하기 [Python, 파이썬]

YoonJuHan 2024. 1. 3. 09:33
  • 문제 : https://www.acmicpc.net/problem/1715
  • 🔑 최소 힙
    • 힙에서 가장 작은 수 두 개를 뽑는다. heappop 두 번
    • 뽑아낸 두 수를 더해서 힙에 다시 넣고 합한 값만큼 정답을 올려준다.

 

from heapq import heappop, heappush
import sys
input = sys.stdin.readline

n = int(input())

heap = []
for _ in range(n):
    heappush(heap, int(input()))

answer = 0
while len(heap) >= 2:
    x = heappop(heap) + heappop(heap)
    heappush(heap, x)
    answer += x

print(answer)
Comments