题解 | #哈夫曼树#
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
#include <queue> #include <iostream> using namespace std; int main() { int val,n,sum; while(scanf("%d",&n)!=EOF){ sum=0; priority_queue<int,vector<int>,greater<int> > myQueue; //小顶堆 for(int i=0;i<n;i++){ cin>>val; myQueue.push(val); } while(myQueue.size()>1){ //若初始size为2,弹一个出来变为1,这时不会立即退出循环,而是会再弹一个 int a=myQueue.top(); myQueue.pop(); int b=myQueue.top(); myQueue.pop(); int c=a+b; sum+=c; myQueue.push(c); } printf("%d\n",sum); } return 0; }