题解 | #哈夫曼树#

哈夫曼树

http://www.nowcoder.com/questionTerminal/162753046d5f47c7aac01a5b2fcda155

#include<iostream>
#include<queue>
using namespace std;

int main(){
  int n;
  while(scanf("%d",&n)!=EOF){
    priority_queue<int, vector<int>, greater<int> >H;//小根堆的优先队列
    while(n--){
      int x;
      scanf("%d",&x);
      H.push(x);
    }
    int ans=0;
    while(H.size()>1){
      int a=H.top();
      H.pop();
      int b=H.top();
      H.pop();
      ans+=a+b;//累加非叶子结点
      H.push(a+b);//新节点入队
    }
    printf("%d\n",ans);
  }
  return 0;
}


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务