可参考priority_queue(优先队列)讲解_priority------queue-CSDN博客
用优先队列(堆-完全二叉树)来实现哈夫曼树,每次取小根堆队头两元素相加为一个,pop完再push进去,相当于模拟哈夫曼树的构造了。
代码如下:
cpp
#include <bits/stdc++.h>
using namespace std;
#define fs first
#define sc second
#define endl '\n'
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;
void solve(){
priority_queue<int,vector<int>,greater<int>> q;//小根堆
int n;cin>>n;
for(int i=0;i<n;i++)
{
int x;cin>>x;
q.push(x);
}
int ans=0;
while(q.size()>1)
{
//取最小的两个元素
int a=q.top();q.pop();
int b=q.top();q.pop();
ans+=(a+b);
q.push(a+b);
}
cout<<ans<<endl;
}
int main(){
cin.tie(0);
cout.tie(0);
ios::sync_with_stdio(0);
int t;
t=1;
while (t--)
{
solve();
}
return 0;
}