Openjudge Huffman Coding Tree

Source: Internet
Author: User
Huffman Coding Tree
View Submit Statistics Questions
Total time limit: 1000ms memory limit: 65535kB
Describe




Constructs an extended binary tree with n external nodes, each outer node Ki has a WI counterpart, as the right of the external node. The sum of the weighted external path length of the leaf node of this extended binary tree is minimal:
Min (W1 * L1 + W2 * L2 + W3 * L3 + ... + Wn * Ln)
Wi: The weight of each node.
Li: The distance from the root node to the first outer leaf node.
Calculates the sum of the minimum external path lengths programmatically.
Input
The first line enters an integer t that represents the number of groups of test data.
For each set of test data, the first line enters an integer n, the number of external nodes. The second line enters n integers, representing the weights of each external node.
2<=n<=100
Output
Total output minimum external path length.
Sample input
2
3
1 2 3
4
1 1 3 5
Sample output
9
17
Tips
Only examine the establishment of Huffman tree, the data range is small, can not need to use heap structure.

However, it is encouraged to use the heap of the first problem to find the smallest and second small elements.

#include <iostream>

using namespace std;
#define MaxSize

Sort (int s[],int n)
{
    int i, J;
    int t;
    for (i = 0; i < n; i++)
    {for
        (j = 0; J < n-i-1; j +)
        {
            if (S[j] < S[j + 1])
            {
                T = s[j ];
                S[J] = s[j + 1];
                S[j + 1] = t; 

}}} int deal (int s[],int N)
{
    if (n = 1) return
        0;
    else
    {
        sort (s,n);
        S[n-2] = s[n-1] + s[n-2];
        return S[n-2] + deal (s,n-1);
    }
}

int main ()
{
    int n, NC;
    int s[maxsize];
    CIN >> N;
    while (n--)
    {
        int i;
        Cin >> NC;
        for (i = 0; i < NC; i++)
        {
            cin>>s[i];
        }
        cout << Deal (S,NC) << Endl;
    }
    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.