Acwing
Topic description
ideas
The small root heap of the priority queue needs to be used to ensure that the smallest heap is merged each time, and it supports deletion and insertion exchange operations, so that the value on the left side of each time is the smallest.
C++ code
#include <bits/stdc++.h>
using namespace std;
int main () {
int n;
cin >> n;
priority_queue<int, vector<int>, greater<int>> heap;
while (n --) {
int x;
cin >> x;
heap.push(x);
}
int res = 0;
while (heap.size() > 1) {
int x = heap.top();
heap.pop();
int y = heap.top();
heap.pop();
res += x + y;//合并
heap.push(x + y);
}
cout << res << endl;
return 0;
}