백준 1715번 카드 정렬하기

highway92·2021년 9월 14일
0

백준

목록 보기
6/27

문제출처 : https://www.acmicpc.net/problem/1715

greedy 알고리즘

풀이과정

  1. 최소값을 구하라는 문제는 보통 heap 자료구조를 쓰는 경우가 많았다.(그래서 빠르게 생각해낼 수 있었다.)

  2. result라는 리스트에 숫자를 받을때 마다 heappush 해준다.

  3. result 안에 숫자가 1개만 남을 때 까지 while문을 통해 반복해준다.

정답코드

import heapq
import sys
def solve():
    result=[]
    answer=0
    n=int(input())

    for i in range(n):
        num = int(sys.stdin.readline())
        heapq.heappush(result,num)
    while len(result) != 1:
        a=heapq.heappop(result)
        b=heapq.heappop(result)
        heapq.heappush(result, a+b)
        answer+= a+b

    return print(answer)

solve()
profile
웹 개발자로 활동하고 있습니다.

0개의 댓글