UVa-10954

Posted Kiven#5197

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVa-10954相关的知识,希望对你有一定的参考价值。

 

10954 - Add All

Time limit: 3.000 seconds

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, let’s 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 12 and 3. There are several ways –

 

1 + 2 = 3, cost = 3

3 + 3 = 6, cost = 6

Total = 9

1 + 3 = 4, cost = 4

2 + 4 = 6, cost = 6

Total = 10

2 + 3 = 5, cost = 5

1 + 5 = 6, cost = 6

Total = 11

 

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

 

Input

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.

 

Output

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

 

样例输入:

 

3

1 2 3

4

1 2 3 4

0

 

样例输出:

9

19

 

 

题意:

给定n个数,任意两数相加的花费为相加的和,和放入队中继续相加,求全部加完时的最小值。

 

定义优先队列最小值优先,队首两元素相加并分别出队,总值+=和,若队列此时不为空,则将和入队,继续循环直到队列为空。

 

附AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;
 7 
 8 struct cmp{//重载“()”运算符,自定义最小值优先 
 9     bool operator()(int &a,int &b){
10         return a>b;
11     }
12 };
13 
14 int n,a;
15 
16 int main(){
17     priority_queue<int,vector<int>,cmp> q; //定义优先队列q 
18     while(~scanf("%d",&n)&&n!=0){
19         for(int i=0;i<n;i++){//入队 
20             scanf("%d",&a);
21             q.push(a);
22         }
23         int sum=0;
24         while(q.size()){//当队列不为空时 
25             int x=q.top();//最小的两个相加并出队 
26             q.pop();
27             int y=q.top();
28             q.pop();
29             sum+=x+y;//总和 
30             if(q.size())//若加完队列不为空,则将和入队 
31             q.push(x+y);
32         }
33         printf("%d\n",sum);
34     }
35     return 0;
36 }

 

以上是关于UVa-10954的主要内容,如果未能解决你的问题,请参考以下文章

uva-10954-贪心

UVa10954 Add All (Huffman编码,优先队列)

UVA-10954 Add All

UVa 10954 - Add All

UVA 10954 Add All

UVA - 10954 A - Add All