Calculate the height of the Huffman number

Source: Internet
Author: User

Question: given n integers, calculate the height of the corresponding user tree

Consider the process of establishing the Haffman tree: each time you select the smallest two nodes from all nodes to form a new node, the weight of the new node is the sum of the weights of the two nodes, and delete the two
Node. Therefore, we can use an array.
1. Sort the array in descending order (the smallest two are at the end)
2. Merge the last two elements of the array into one. The number of layers adds 1 to the maximum number of layers of the original two elements.
3. Reduce the length of the array by one.
4. Sort the new array again --> Step 1
Loop until the array length is 1

 

Struct Node {
Int value;
Int layer;
};

// Sort in descending order
Int cmp (const void * a, const void * B)
{
Struct Node * t1 = (struct Node *) a, * t2 = (struct Node *) B;
Return (t1-> value <= t2-> value );
}

Int TreeHeight (int * a, int n)
{
Struct Node * p = new struct Node [n];
For (int I = 0; I <n; I ++)
{
P [I]. value = a [I];
P [I]. layer = 0;
}
While (n> 1)
{
Qsort (p, n, sizeof (struct Node), cmp );
P [N-2]. value + = p [n-1]. value;
P [N-2]. layer = (p [N-2]. layer> = p [n-1]. layer? P [N-2]. layer: p [n-1]. layer) + 1;
N --;
}

Return p [0]. layer;
}


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.