题目描述
思路
需要用到优先队列 的小根堆,保证每次合并最小的堆,并且支持删除插入交换操作,使得每次左边的值最小。
C++代码
#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;
}