Combine Fruit Huffman tree--priority queue Solution Huffman

Source: Internet
Author: User
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;
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.