/* *Copyright (c) 2014,烟台大学计算机学院 *All rights reserved. *文件名称:Annpion.cpp *作者:王耀鹏 *完成日期:2016年1月9日 *版本号:v1.0 * *问题描述:哈夫曼编码 *输入描述:无 *输出描述:输出哈夫曼编码 */ #include<stdio.h> #include<string.h> #define N 50 typedef struct { char data; double weight; int parent; int lchild; int rchild; }HTNode; typedef struct { char cd[N]; int start; }HCode; void CreateHT(HTNode ht[],int n) { int i,k,lnode,rnode; double min1,min2; for(i=0;i<2*n-1;++i) ht[i].parent=ht[i].lchild=ht[i].rchild=-1; for(i=n;i<2*n-1;++i) { min1=min2=32767; lnode=rnode=-1; for(k=0;k<i;++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[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) { int i,f,c; HCode hc; for(i=0;i<n;++i) { hc.start=n; 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++; //start指向哈夫曼编码最开始字符 hcd[i]=hc; } } void DispHCode(HTNode ht[],HCode hcd[],int n) { int i,j,k; double sum=0,m=0; printf(" 输出哈夫曼编码:\n"); for(i=0;i<n;++i) { j=0; printf(" %c:\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 平均长度=%g\n",1.0*sum/m); } int main() { int n=8,i; //n表示初始字符串的个数 char str[]= {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; double fnum[]= {0.07,0.19,0.02,0.06,0.32,0.03,0.21,0.1}; HTNode ht[2*N-1]; HCode hcd[N]; for (i=0; i<n; i++) { 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"); return 0; }
运行结果: