[AcWing 148] 合并果子


点击查看代码
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int n, res;
priority_queue<int,vector<int>,greater<int>> heap;
int main()
{
cin >> n;
for (int i = 0; i < n; i ++) {
int x;
cin >> x;
heap.push(x);
}
while (heap.size() > 1) {
int t1 = heap.top();
heap.pop();
int t2 = heap.top();
heap.pop();
res += t1 + t2;
heap.push(t1 + t2);
}
cout << res << endl;
return 0;
}
- 算法思路
建立哈夫曼树:每次从集合中取出最小的两个元素进行合并,并把合并后的结果放入集合中,直到集合中只剩一个元素 - 利用小根堆来维护集合中的最小值

浙公网安备 33010602011771号