/* Exp7-6.cpp */
# Include <stdio. h>
# Include <string. h>
# Define N 50/* Number of leaf nodes */
# Define M 2 * N-1/* Total number of nodes in the tree */
Typedef struct
{
Char data [5];/* Number of knots */
Int weight;/* weight */
Int parent;/* parent node */
Int lchild;/* left child node */
Int rchild;/* right child node */
} Htnode;
Typedef struct
{
Char CD [N];/* store the Harman Code */
Int start;
} Hcode;
Void createht (htnode HT [], int N)/* construct a Harman tree */
{
Int I, K, lnode, rnode;
Int min1, min2;
For (I = 0; I <2 * n-1; I ++)/* set the initial values of the relevant fields of all nodes-1 */
HT [I]. Parent = HT [I]. lchild = HT [I]. rchild =-1;
For (I = N; I <2 * n-1; I ++)/* construct a Harman tree */
{
Min1 = min2 = 32767;/* the location of the two nodes with the minimum weight of lnode and rnode */
Lnode = rnode =-1;
For (k = 0; k <= I-1; k ++)
If (HT [K]. Parent =-1)/* Only search for nodes that have not yet constructed a binary tree */
{
If (HT [K]. weight <min1)
{
Min2 = min1; rnode = lnode;
Min1 = HT [K]. weight; lnode = K;
}
Else if (HT [K]. weight <min2)
{
Min2 = HT [K]. weight; rnode = K;
}
}
HT [lnode]. Parent = I; HT [rnode]. Parent = I;
HT [I]. Weight = HT [lnode]. Weight + HT [rnode]. weight;
HT [I]. lchild = lnode; HT [I]. rchild = rnode;
}
}
Void createhcode (htnode HT [], hcode HCD [], int N)/* construct the Harman encoding */
{
Int I, F, C;
Hcode HC;
For (I = 0; I <n; I ++)/* calculate the Harman Encoding Based on the Harman tree */
{
HC. Start = N; C = I;
F = HT [I]. parent;
While (F! =-1)/* sequentially until the root node */
{
If (HT [f]. lchild = C)/* process the left child node */
HC. CD [HC. Start --] = '0 ';
Else/* process the right child node */
HC. CD [HC. Start --] = '1 ';
C = f; F = HT [f]. parent;
}
HC. Start ++;/* start points to the start character of the Harman encoding */
HCd [I] = HC;
}
}
Void disphcode (htnode HT [], hcode HCD [], int N)/* output Harman encoding */
{
Int I, K;
Int sum = 0, m = 0, J;
Printf ("output Harman encoding: \ n");/* output Harman encoding */
For (I = 0; I <n; I ++)
{
J = 0;
Printf ("% s: \ t", HT [I]. data );
For (k = HCD [I]. Start; k <= N; k ++)
{
Printf ("% C", HCD [I]. CD [k]);
J ++;
}
M + = HT [I]. weight;
Sum + = HT [I]. Weight * J;
Printf ("\ n ");
}
Printf ("\ n average length = % G \ n", 1.0 * sum/M );
}
Void main ()
{
Int n = 15, I;
Char * STR [] = {"the", "of", "A", "to", "and", "in", "that", "he ", "is", "",
"On", "for", "his", "are", "be "};
Int fnum [] = {1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123 };
Htnode HT [m];
Hcode HCD [N];
For (I = 0; I <n; I ++)
{
Strcpy (HT [I]. Data, STR [I]);
HT [I]. Weight = fnum [I];
}
Printf ("\ n ");
Createht (HT, N );
Createhcode (HT, HCD, N );
Disphcode (HT, HCD, N );
Printf ("\ n ");
}