본문 바로가기
PS(Problem Solving)/백준_BOJ

[백준] 1715번 - 카드 정렬하기 (C++/파이썬) 문제 및 풀이

by 초코칩프라푸치노 2021. 4. 14.

문제) 백준 - 우선순위 큐 (Priority Queue) - 카드 정렬하기

->www.acmicpc.net/problem/1715

 

1715번: 카드 정렬하기

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

www.acmicpc.net

 

C++ 소스 코드)

 

#include <bits/stdc++.h>
#define endl "\n"
#define ll long long
using namespace std;
int main() {
ios::sync_with_stdio(false);
cout.tie(0); cin.tie(0);
priority_queue<int, vector<int>, greater<int>> q;
int n; cin >> n;
for (int i = 0; i < n; ++i) {
int temp; cin >> temp;
q.push(temp);
}
int res = 0;
int a, b;
while (q.size() > 1) {
a = q.top(); q.pop();
b = q.top(); q.pop();
res += (a + b);
q.push(a + b);
}
cout << res << endl;
return 0;
}
view raw 1715.cpp hosted with ❤ by GitHub

파이썬 소스 코드)

 

import heapq
n = int(input())
card = []
for _ in range(n):
heapq.heappush(card, int(input()))
total = 0
if n == 1:
print(total)
else:
while len(card) > 1:
num1 = heapq.heappop(card)
num2 = heapq.heappop(card)
total += (num1 + num2)
heapq.heappush(card, num1 + num2)
print(total)
view raw 1715.py hosted with ❤ by GitHub

 

 

반응형

댓글