문제) 백준 - 우선순위 큐 (Priority Queue) - 카드 정렬하기
->www.acmicpc.net/problem/1715
1715번: 카드 정렬하기
정렬된 두 묶음의 숫자 카드가 있다고 하자. 각 묶음의 카드의 수를 A, B라 하면 보통 두 묶음을 합쳐서 하나로 만드는 데에는 A+B 번의 비교를 해야 한다. 이를테면, 20장의 숫자 카드 묶음과 30장
www.acmicpc.net
C++ 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
파이썬 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 10422번 - 괄호 (C++) 문제 및 풀이 (0) | 2021.06.29 |
---|---|
[백준] 14499번 - 주사위 굴리기 (C++) 문제 및 풀이 (0) | 2021.06.29 |
[백준] 11279번 - 최대 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 1927번 - 최소 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 1181번 - 단어 정렬 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
댓글