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