提交时间:2026-06-17 19:38:13
运行 ID: 91855
#include <iostream> #include <vector> #include <queue> using namespace std; int main() { // 优化IO ios::sync_with_stdio(false); cin.tie(NULL); int n; if (!(cin >> n)) return 0; // 使用小顶堆:greater<int> 使最小的元素在顶部 priority_queue<int, vector<int>, greater<int>> pq; for (int i = 0; i < n; ++i) { int val; cin >> val; pq.push(val); } long long total_cost = 0; // 当堆中元素超过1个时,继续合并 while (pq.size() > 1) { // 取出两个最小的数 int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); // 计算当前合并费用 int sum = a + b; // 累加总费用 total_cost += sum; // 将和放回堆中 pq.push(sum); } cout << total_cost << endl; return 0; }