import sys
import heapq
scan = sys.stdin.readline
printf = sys.stdout.write
def solution():
T = int(scan())
for t in range(T):
tc()
def tc():
K = int(scan())
chapter_lengths = list(map(int, scan().split()))
heapq.heapify(chapter_lengths)
total_cost = 0
while len(chapter_lengths) > 1:
chapterA = chapter_lengths[0]; heapq.heappop(chapter_lengths)
chapterB = chapter_lengths[0]; heapq.heappop(chapter_lengths)
cost = chapterA + chapterB
heapq.heappush(chapter_lengths, cost)
total_cost += cost
printf("%d\n" % total_cost)
solution()
문자열 합치기에 제출한 코드이다.
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
typedef priority_queue<int, vector<int>, greater<int>> intQ;
void tc();
int main() {
int C;
scanf(" %d\n", &C);
for (int i = 0; i < C; i++) {
tc();
}
return 0;
}
void getInput(int &n, vector<int> &lengths) {
scanf(" %d", &n);
for (int i = 0; i < n; ++i) {
int len;
scanf(" %d", &len);
lengths.push_back(len);
}
}
void initQueue(intQ &pq, vector<int> &lengths) {
for (auto len: lengths) {
pq.push(len);
}
}
void tc() {
int n;
vector<int> lengths;
getInput(n, lengths);
intQ pq;
initQueue(pq, lengths);
int totalCost = 0;
while (pq.size() > 1) {
int dest = pq.top(); pq.pop();
int src = pq.top(); pq.pop();
int cost = dest + src;
pq.push(cost);
totalCost += cost;
}
printf("%d\n", totalCost);
}
파일 합치기 3에 제출한 코드이다.