标题:[求助]这个是输出哈夫曼码的程序,但是有点问题.........
只看楼主
anlingdiao
Rank: 1
等 级:新手上路
帖 子:23
专家分:0
注 册:2007-4-4
 问题点数:0 回复次数:0 
[求助]这个是输出哈夫曼码的程序,但是有点问题.........
帮帮偶看看!
#include "stdio.h"
#include "stdlib.h"
#include "limits.h"
struct HTNode
{unsigned int weight;
unsigned int parent,lchild,rchild;
};
typedef struct HTNode *HuffmanTree;
typedef char **HuffmanCode;
int min(HuffmanTree t,int i) // 老说这句有问题,好象是语法错误!
{int j,flag;
unsigned int k=UINT_MAX;
for(j=1;j<=i;j++)
if(t[j].weight<k && t[j].parent==0)
{ k=t[j].weight;
flag=j;}
t[flag].parent=1;
return flag;
}
void select(HuffmanTree t,int i,int *s1,int *s2)
{int j;
s1=min(t,i);
s2=min(t,i);
if(s1>s2)
{j=s1;
s1=s2;
s2=j;
}
}
void HuffmanCoding(HuffmanTree HT,HuffmanCode HC,int *w,int n)
{int m,i,s1,s2,start;
unsigned c,f;
HuffmanTree p;
char *cd;
if(n<=1)
return;
m=2*n-1;
for(p=HT+1,i=1;i<=n;++i,++p,++w)
{(*p).weight=*w;
(*p).parent=0;
(*p).lchild=0;
(*p).rchild=0;
}
for(;i<=m;++i,++p)
(*p).parent=0;
for(i=n+1;i<=m;++i)
{select(HT,i-1,s1,s2);
HT[s1].parent=HT[s2].parent=i;
HT[i].lchild=s1;
HT[i].rchild=s2;
HT[i].weight=HT[s1].weight+HT[s2].weight;
}
cd=(char *)malloc(n*sizeof(char));
cd[n-1]='\0';
for(i=1;i<=n;i++)
{star=n-1;
for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent)
if(HT[f].lchild==c)
cd[--start]='0';
else
cd[--start]='1';
HC[i]=(char *)malloc((n-star)*sizeof(char));
strcpy(HC[i],&cd[star]);
}
free(cd);
}
main()
{HuffmanTree HT;
HuffmanCode HC;
int *w,n,i;
printf("please input total of weight:");
scanf("%d",&n);
HT=(HuffmanTree)malloc((n+1)sizeof(struct HTNode));
HC=(HuffmanCode)malloc((n+1)sizeof(char *));
w=(int *)malloc(n*sizeof(int));
printf("please input weight one by one :\n",n);
for(i=0;i<n-1;i++)
scanf("%d",w+i);
HuffmanCoding(HT,HC,w,n);
for(i=1;i<=n;i++)
puts(HC[i]);
}
搜索更多相关主题的帖子: 哈夫曼 输出 
2007-05-30 20:48



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-143637-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.426871 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved