2213: Combine Fruits
Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
![]() | 8s | 8192K | 1692 | 268 | Special Test |
After culling his most favorite fruits from the trees in an orchard, Fen Nec, a mischievous monkey, is confused of the way in which he can combine these piles of fruits into one in the most laborsaving manner. Each turn he can merely combine any two piles into a larger one. Obviously, by combining N-1 times for N piles of fruits, one pile results eventually. It always takes Fen Nec a certain quantity of units of stamina, which equals to the sum of the amounts of fruits in each of the two piles combined, to complete a combination. For instance, given three piles of fruits, containing 1, 2, and 9 fruits respectively, the combination of 1 and 2 would cost 3=1+2 units of stamina, and two piles-3 and 9-are resulted; finally, combining them would cost another 12=3+9 units of stamina, and the total units of stamina taken in the whole procedure is 15=3+12. Surely there are many a possible means to combine these three piles; however, it can be proved that 15 is the minimum amount of units of stamina in demand, and that is what your program is required to do.
Input
The input file consists of only ONE test case. The first line contains an integer N (<=10000), indicating the number of piles, and the second line contains N integers, each of which represents the amount of fruits in a pile.
Output
Your program should print the minimum amount of units of stamina that are required to combine these piles of fruits into one.
Sample Input
3 1 2 9
Sample Output
15
This problem is used for contest: 31 147
#include<iostream>
#include<queue>
using namespace std;
int main()
{
priority_queue<int ,vector<int>,greater<int> >q;
int n,x;
while(cin>>n)
{
while(n--) {cin>>x;q.push(x);}
int sum=0;
while(q.size()>1)
{
x=q.top();
q.pop();
x+=q.top();
sum+=x;
q.pop();
q.push(x);
}
cout<<sum<<endl;
}
return 0;
}