UVA 10954 Add All 哈夫曼编码

时间:2021-01-25 18:04:56

题目链接:

题目

Add All

Time Limit:3000MS

Memory Limit:0KB

问题描述

Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves

condescended, to write a C/C++ program just to add a set of numbers. Such a problem will simply

question your erudition. So, lets add some flavor of ingenuity to it.

Addition operation requires cost now, and the cost is the summation of those two to be added. So,

to add 1 and 10, you need a cost of 11. If you want to add 1, 2 and 3. There are several ways

1 + 2 = 3, cost = 3 1 + 3 = 4, cost = 4 2 + 3 = 5, cost = 5

3 + 3 = 6, cost = 6 2 + 4 = 6, cost = 6 1 + 5 = 6, cost = 6

Total = 9 Total = 10 Total = 11

I hope you have understood already your mission, to add a set of integers so that the cost is minimal.

输入

Each test case will start with a positive number, N (2 ≤ N ≤ 5000) followed by N positive integers

(all are less than 100000). Input is terminated by a case where the value of N is zero. This case should

not be processed.

输出

For each case print the minimum total cost of addition in a single line.

样例

input

3

1 2 3

4

1 2 3 4

0

output

9

19

题意

给你n个数,每次合并两个数,贡献值为这两个数的和,问如何使总的贡献值最小。

题解

越早加的数,被加的次数会越多(早加的数虽然合并了,但它的贡献还在,只是和其他数绑定在一起了)。那么我们当然是贪心让越小的数越早加了。

如果你把一个数被加的次数看成高度的话,那这道题就是赤裸裸的哈夫曼树,严格的贪心证明可以参考第一本白皮书,或者网上搜一下应该有。

代码

#include<iostream>
#include<cstdio>
#include<queue>
#include<functional>
using namespace std; typedef long long LL;
int n; int main(){
while(scanf("%d",&n)==1&&n){
LL ans=0;
priority_queue<int,vector<int>,greater<int> > pq;
for(int i=0;i<n;i++){
int x; scanf("%d",&x);
pq.push(x);
}
for(int i=0;i<n-1;i++){
int x=pq.top(); pq.pop();
int y=pq.top(); pq.pop();
ans+=x+y;
pq.push(x+y);
}
printf("%lld\n",ans);
}
return 0;
}