[백준] 1715 카드 정렬하기

ganta·2021년 3월 18일
0

알고리즘 문제해결

목록 보기
7/24

✔️ 문제 링크

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

💡 핵심 아이디어

1️⃣ 결국에는 최소값을 구하는 문제였음으로 탐욕적으로 카드 뭉치에서 계속 최소 개수의 카드뭉치를 2개 뽑아서 더해주워 카드 뭉치수의 수를 줄이고 카드 뭉치가 1일 때까지 반복하여 누적값을 산출하면 된다.

2️⃣ 초기 카드뭉치가 1개인 경우의 예외처리를 해 준다.

⭐️ 소스코드

import heapq

if __name__ == '__main__':
    N = int(input())
    heap = list()
    for i in range(N):
        num = int(input())
        heapq.heappush(heap, num)

    if N == 1:
        print(0)
    else:
        ans = 0
        while len(heap) != 1:
            temp_sum = heapq.heappop(heap) + heapq.heappop(heap)
            ans += temp_sum
            heapq.heappush(heap, temp_sum)
        print(ans)
profile
한걸음씩 꾸준히

0개의 댓글