#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
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) //如果当前堆中size大于1,则进行循环
{
int a=heap.top();heap.pop(); //将堆中最小的两个值取出来,并删掉
int b=heap.top();heap.pop();
res+=a+b; //res 为答案,更新res=res+堆中最小的两个值之和
heap.push(a+b); //将堆中最小的两个值之和放入堆中
}
cout<<res<<endl; //输出res
return 0;
}
acwing 贪心之哈夫曼树 合并果子
最新推荐文章于 2024-09-06 10:38:06 发布