UVa 10954 全部相加(Huffman编码)

https://vjudge.net/problem/UVA-10954

题意:有n个数的集合S,每次可以从S中删除两个数,然后把它们的和放回集合,直到剩下一个数。每次操作的开销等于删除的两个数之和,求最小开销。

思路:Huffman编码。

 1 #include<iostream> 
 2 #include<queue>
 3 using namespace std;
 4 
 5 struct cmp
 6 {
 7     bool operator()(const int a, const int b) const
 8     {
 9         return a > b;
10     }
11 };
12 
13 int main()
14 {
15     //freopen("D:\\txt.txt", "r", stdin);
16     int n;
17     while (cin >> n && n)
18     {
19         priority_queue<int,vector<int>,cmp> q;
20         int ans = 0, a;
21         for (int i = 0; i < n; i++)
22         {
23             cin >> a;
24             q.push(a);
25         }
26         for (int i = 0; i < n - 1; i++)
27         {
28             int b = q.top(); q.pop(); 
29             int c = q.top(); q.pop();  
30             q.push(b + c);
31             ans += b + c;
32         }
33         cout << ans << endl;
34     }
35     return 0;
36 }

 

posted @ 2017-01-29 09:23  Kayden_Cheung  阅读(233)  评论(0编辑  收藏  举报
//目录