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 }

 

转载于:https://www.cnblogs.com/zyb993963526/p/6357336.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值