문제풀이/그리디

[파이썬] [그리디] 백준 1715 카드 정렬하기

승무_ 2023. 4. 10. 19:53

문제

https://www.acmicpc.net/problem/1715

 

1715번: 카드 정렬하기

정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장

www.acmicpc.net

코드

import heapq

n=int(input())
array=[int(input()) for _ in range(n)]

heapq.heapify(array)
result=0
while len(array)>1:
    t1=heapq.heappop(array)
    t2=heapq.heappop(array)
    temp=t1+t2
    result+=temp
    heapq.heappush(array,temp)

print(result)

생각 정리

n이 10만인것을 확인 못하고 dp를 통해 해결하려다 메모리 초과가 떴다....