题解 | #哈夫曼树#
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
//1+2 + 3+2 + 5+5 + 10+9 =37 #include <iostream> #include <queue> using namespace std; int main() { int n; while(cin>>n) { priority_queue<int,vector<int>,greater<>> q;//从小到大排 for(int i=1;i<=n;i++) { int a;cin>>a; q.push(a); } int answer=0; while(q.size()>1) { int a=q.top(); q.pop(); answer+=a; int b=q.top(); q.pop(); answer+=b; q.push(a+b); } cout<<answer<<endl; } }