51nod1117(简单huffman tree)

题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1117

 

题意:中文题诶~

 

思路:简单huffman tree

维护一个优先队列,每次合并两个最小元素。。

 

代码:

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 
 5 int main(void){
 6     ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
 7     int n, x, ans=0;
 8     priority_queue<int, vector<int>, greater<int> > q;
 9     cin >> n;
10     for(int i=0; i<n; i++){
11         cin >> x;
12         q.push(x);
13     }
14     while(q.size()>1){
15         int cnt1=q.top();
16         q.pop();
17         int cnt2=q.top();
18         q.pop();
19         int cnt=cnt1+cnt2;
20         ans+=cnt;
21         q.push(cnt);
22     }
23     cout << ans << endl;
24     return 0;
25 }

 

posted @ 2017-01-25 19:24  geloutingyu  阅读(167)  评论(0编辑  收藏  举报