Tree-heap structure exercises--Combining fruit Huffman tree time limit:1000ms Memory limit:65536kb 64bit IO format:%lld &%llu Submit Status
Description in an orchard, many have already beaten all the fruit, and according to the different kinds of fruit into a different heap. Many decided to synthesize all the fruits into a heap. Each time a merger, a lot can combine two piles of fruit together, the energy consumption equals two of the weight of the fruit of the sum. It can be seen that all the fruit after n-1 the merger, there is only a pile. The total amount of energy consumed in merging the fruit equals the physical exertion of each merger.
The first line of Input is an integer n (1<=n<=10000) that represents the number of types of fruit. The second row contains n integers, separated by spaces, and the first AI (1<=ai<=20000) is the number of the first fruit.
Output outputs include a line that contains only one integer, which is the minimum physical cost. The input data guarantees that this value is less than 2^31.
Sample Input
3
1 2 9
Sample Output
15
To make the most of the effort, the two piles with the smallest quality will be moved every time they are transported. Use the priority queue, the team top puts the minimum value, each fetch two smallest elements, find out and then join the queue.
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm >
#include <queue>
using namespace std;
struct CMP
{
bool operator () (const int &a,const int& b)
{return
a > b;
}}
;
int main ()
{
priority_queue<int,vector<int>,cmp> q;
int n,i,j,k,sum = 0;
scanf ("%d", &n);
for (i = 0;i < n;i++)
{
scanf ("%d", &k);
Q.push (k);
}
while (Q.size ()!= 1)
{
int x1, x2;
X1 = Q.top ();
Q.pop ();
x2 = Q.top ();
Q.pop ();
Sum + = (x1 + x2);
Q.push (X1+X2);
}
printf ("%d\n", sum);
return 0;
}