#include
#define MAX 100
#define MAXVALUE 500
typedef struct
{
int weight;
int parent,lchild,rchild;
}node; /*哈夫曼树结点类型*/
/*-----------------------------以下部分定义哈夫曼编码存储结构-------------------------*/
typedef struct{
int start; //存放起始位置
char bits[10+1]; //存放编码位串
}codetype;
typedef struct{
char symbol; //存储字符
codetype code;
}element;
void getMinElementLocal(node t[] ,int num , int *minLocal1 , int *minLocal2) ;
/*---------------------------------------------------------------------------------------------------*/
/*构建哈夫曼树。n为构建哈夫曼树的叶子结点个数,数组w存储每个叶子的权值,数组t存储构建好的哈夫曼树*/
void huffman(int n,int w[],node t[])
{
int m = 0 ;
int minLocal1 , minLocal2 ;
int i = 0 ;
node * nodes = NULL ;
if(n == 0) return ;
m = 2*n -1 ;
for(i = 1 ; i <= n ; i ++){
t[i].weight = w[i] ;
t[i].lchild = t[i].parent = t[i].rchild = -1 ;
}
for(; i <= m ; i ++){
t[i].weight = 0 ;
t[i].lchild = t[i].parent = t[i].rchild = -1 ;
}
for(i = 1 ; i <= n-1 ; i ++){
minLocal1 = minLocal2 = -2 ;
getMinElementLocal(t , n+i , &minLocal1 , &minLocal2) ;
t[n+i].weight = t[minLocal1].weight + t[minLocal2].weight ;
t[n+i].lchild = minLocal1 ;
t[n+i].rchild = minLocal2 ;
t[minLocal1].parent = n+i ;
t[minLocal2].parent = n+i ;
}
}
void getMinElementLocal(node t[] ,int num , int *minLocal1 , int *minLocal2){
int i = 0 ;
int temp1 = MAXVALUE ;
int temp2 = MAXVALUE ;
*minLocal1 = *minLocal2 = 0 ;
for(i = 1 ; i < num ; i ++){
if(t[i].weight <= temp1 && t[i].parent == -1){
temp1 = t[i].weight ;
*minLocal1 = i ;
}
}
for(i = 1 ; i < num ; i ++){
if(t[i].weight <= temp2 && t[i].parent == -1 && i != *minLocal1){
temp2 = t[i].weight ;
*minLocal2 = i ;
}
}
}
/*---------------------------------------------------------------------------------------------------*/
/*根据哈夫曼树,求哈夫曼编码表。tree存储哈夫曼树,table存储哈夫曼编码表,n为哈夫曼树叶子个数*/
void sethufcode(node tree[],element table[],int n)
{
int i,j,s,f; /* 和f分别指示tree中孩子和双亲的位置*/
codetype c;/*时存放编码 */
for(i=1;i<=n;i++)/*次求叶子tree[i]的编码 */
{
printf("%d:",tree[i].weight);
c.start=n+1;
s=i;/*叶子tree[i]开始上溯 */
while(tree[s].parent != -1)/*至上溯到树根为止 */
{
f=tree[s].parent ;
c.bits[--c.start]= (s == tree[f].lchild)?'0':'1';
s=f;
}
for(j=c.start ;j printf("%c",c.bits[j]); printf("/n"); table[i].code=c;/*时编码复制到最终位置 */ } } /*---------------------------------------------------------------------------------------------------*/ void main() { node t[100]; int i,n,w[100]; element m[100]; printf("请输入结点数:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("请输入第%d个结点权重:", i); scanf("%d",&w[i]); } /*构造哈夫曼树*/ huffman(n ,w , t) ; printf("序号 权重 双亲 左孩 右孩/n"); /*输出哈夫曼树*/ for(i=1;i<(2*n);i++) printf("%-5d%-5d%-5d%-5d%-5d/n",i,t[i].weight,t[i].parent,t[i].lchild,t[i].rchild); sethufcode(t,m,n); /*构造并输出哈夫曼编码表*/ }