#include <iostream>
#include <algorithm>
#include<string>
#include<queue>
#include<functional>
using namespace std;
//使用优先队列实现最小堆
priority_queue<int, vector<int>, greater<int>>q;
void main()
{
int n;
int a, b, res;
while (cin >> n)
{
int a;
res = 0;
while (!q.empty())q.pop();
while (n--)
{
cin >> a;
q.push(a);
}
while (q.size() > 1){
a = q.top();
q.pop();
b = q.top();
q.pop();
res += a + b;
q.push(a + b);
}
cout << res<< endl;
}
}
本文介绍了一种利用优先队列实现最小堆的数据结构方法,并通过一个具体的C++程序实例展示了如何利用最小堆来解决元素合并的问题。该程序能够接收一系列整数输入,通过不断合并最小的两个数直至只剩下一个数,从而计算出所有合并操作的总成本。
1万+

被折叠的 条评论
为什么被折叠?



