반갑습니다!

[백준] 1715 카드 정렬하기 본문

알고리즘 문제 풀이

[백준] 1715 카드 정렬하기

김덜덜이 2020. 9. 23. 11:38
1715번: 카드 정렬하기
 
www.acmicpc.net

풀이

가장 작은 숫자의 카드끼리 섞어야한다는 것은 직관적으로 알 수 있다. 따라서 우선순위 큐를 사용해서 구현했다.

코드

C++

#include <iostream>
#include <queue>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;
    priority_queue<int, vector<int>, greater<int>> pq;
    for (int i = 0; i < n; i++) {
        int tmp;
        cin >> tmp;
        pq.push(tmp);
    }

    int ans = 0;
    while (pq.size() > 1) {
        int n1 = pq.top();
        pq.pop();
        int n2 = pq.top();
        pq.pop();
        int sum = n1 + n2;
        ans += sum;
        pq.push(sum);
    }
    cout << ans << '\n';
    return 0;
}

Python3

import sys
import heapq

n = int(sys.stdin.readline().strip())
card = []

for i in range(n):
    heapq.heappush(card, int(sys.stdin.readline().rstrip()))

answer = 0
while len(card) > 1:
    a = heapq.heappop(card)
    b = heapq.heappop(card)
    answer += (a + b)
    heapq.heappush(card, a + b)
print(answer)

'알고리즘 문제 풀이' 카테고리의 다른 글

[백준] 1939 중량제한  (0) 2020.09.24
[백준] 1822 차집합  (0) 2020.09.23
[백준] 2012 등수매기기  (0) 2020.09.23
[프로그래머스] 두 개 뽑아서 더하기  (0) 2020.09.22
[프로그래머스] 삼각 달팽이  (0) 2020.09.22