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;
}