#include<stdio.h>
#include<string.h>
#define N 15
typedef struct
{
char data[4];
double weight;
int parent;
int lchild;
int rchild;
}HTNode;
typedef struct
{
char cd[N];
int start;
}HCode;
void CreatHCode(HTNode ht[],HCode hcd[],int n0)
{
int i,f,c;
HCode hc;
for(i=0;i<n0;i++)
{
hc.start=n0;
c=i;
f=ht[i].parent;
while(f!=-1)
{
if(ht[f].lchild==c)
{
hc.cd[hc.start--]='0';
}
else
{
hc.cd[hc.start--]='1';
}
c=f;f=ht[f].parent;
}
hc.start++;
hcd[i]=hc;
}
}
void CreatHT(HTNode ht[],int n0)
{
int i;
int k;
int lnode;
int rnode;
double min1;
double min2;
for(i=0;i<2*n0-1;i++)
{
ht[i].parent=ht[i].lchild=ht[i].rchild=-1;
}
for(i=n0;i<=2*n0-2;i++)
{
min1=min2=32767;
lnode=rnode=-1;
for(k=0;k<=i-1;k++)
{
if(ht[k].parent==-1)
{
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[i].weight=ht[lnode].weight+ht[rnode].weight;
ht[i].lchild=lnode;
ht[i].rchild=rnode;
ht[lnode].parent=i;
ht[rnode].parent=i;
}
}
void Show(HTNode ht[],HCode hcd[],int n)
{
int i;
int k;
int sum=0;
int sumWeight=0;
int j;
printf(" 输出哈夫曼编码:\n");
for(i=0;i<n;i++)
{
j=0;
printf("%s: ",ht[i].data);
for(k=hcd[i].start;k<=n;k++)
{
printf("%c",hcd[i].cd[k]);
j++;
}
sum+=ht[i].weight;
sumWeight+=ht[i].weight*j;
printf("\n");
}
printf(" 平均查找长度=%1.3f",1.000*sumWeight/sum);
}
void Giv(HTNode a[],double b[],char *s[])
{
for(int i=0;i<15;i++)
{
strcpy(a[i].data,s[i]);
a[i].weight=b[i];
}
}
int main()
{
HTNode lev[15];
char *str[15]={"The","of","a","to","and","in","that","he","is","at","on","for","His","are", "be"};
double weight[15]={1192,677,541,518,462,450,242,195,190,181,174,157,138,124,123};
for(int i=0;i<15;i++)
{
strcpy(lev[i].data,str[i]);
lev[i].weight=weight[i];
}
CreatHT(lev,15);
HCode levW[15];
CreatHCode(lev,levW,15);
Show(lev,levW,15);
return 0;
}