哈夫曼编码,最后的编码结果不正确

爱写bug的小邓程序员 2019-05-17 12:27:40
#include<stdio.h>
#include<malloc.h>
#define N 20
#define M 2*N-1
typedef struct node
{
int weight;
int parent;
int lchild;
int rchild;
}huffmanbitree[M+1];
void select(huffmanbitree ht,int i,int *s1,int *s2)
{
int j;
long min1=99999;
long min2=99999;
for(j=1;j<=i;j++)
{
if(ht[j].parent==0) //保证了被选出来的不会再选
{
if(min1>ht[j].weight)
{
min1=ht[j].weight;
*s1=j;
}
}
}
for(j=1;j<=i;j++)
{
if(ht[j].parent==0)
{
if(min2>ht[j].weight&&j!=*s1)
{
min2=ht[j].weight;
*s2=j;
}
}
}
}
void creat(huffmanbitree ht,int w[],int n)
{
int i,m=2*n-1,s1,s2;
for(i=1;i<=n;i++)
{
ht[i].weight=w[i];
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
}
for(i=n+1;i<=m;i++)
{
ht[i].weight=0;
ht[i].parent=0;
ht[i].lchild=0;
ht[i].rchild=0;
}
for(i=n+1;i<=m;i++)
{
select(ht,i-1,&s1,&s2);
ht[i].weight=ht[s1].weight+ht[s2].weight;
ht[i].lchild=s1;ht[i].rchild=s2;
ht[s1].parent=i;ht[s2].parent=i;
}
}
void print(huffmanbitree ht,int n)
{
printf("序号: 权值: 双亲: 左孩子: 右孩子:\n");
for(int i=1;i<=n;i++)
printf("%d %d %d %d %d\n",i,ht[i].weight,ht[i].parent,ht[i].lchild,ht[i].rchild);
}
void creatnode(huffmanbitree ht,int i,int j)
{
j=ht[i].parent ;
if(ht[j].lchild==i)
printf("1");
else
printf("0");
if(ht[j].parent!=0)
{
i=j;
creatnode(ht,i,j);
}
}
void printhuff(huffmanbitree ht,int n)
{
int i,a,j=0;
for(i=1;i<=n;i++)
{
a=i;
creatnode(ht,i,j);
printf("\n");
i=a;
}
}
void main()
{
int i,n,w[N];
huffmanbitree ht;
printf("请输入长度\n");
scanf("%d",&n);
printf("请输入权值\n");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
creat(ht,w,n);
print(ht,2*n-1);
printhuff(ht,n);
}
...全文
182 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Italink 2019-05-17
  • 打赏
  • 举报
回复
该不会是同学吧,昨天的实验课内容 编码可以随便通过一种遍历方式构建,编码有问题,说明构建的树有问题,可以开监视窗口看一下 另外阔以瞄一下我写的 https://blog.csdn.net/qq_40946921/article/details/90267205
  • 打赏
  • 举报
回复
谢谢你的回答。等会我用电脑试试
Italink 2019-05-17
  • 打赏
  • 举报
回复
2个问题,建树的时候左右孩子反了

void creat(huffmanbitree ht, int w[], int n)
{
        //.....
	for (i = n + 1; i <= m; i++)
	{
		select(ht, i - 1, &s1, &s2);
		ht[i].weight = ht[s1].weight + ht[s2].weight;
		ht[i].lchild = s2;
		ht[i].rchild = s1;
		ht[s1].parent = i; ht[s2].parent = i;
	}
}
另外一个问题,输出,由于你是自低往上找,所以需要先找后打印,通过递归堆栈,要在出栈之后才进行输出,修改函数

void creatnode(huffmanbitree ht, int i)		//没有必要设置参数j
{
	int j = ht[i].parent;
	if (ht[j].parent != 0)	{
		creatnode(ht, j);		//向上继续找,由于你是从低部往上,所以应该先找后打印
	}
	if (ht[j].lchild == i)
		printf("0");
	else
		printf("1");
	
}
void printhuff(huffmanbitree ht, int n){
	int i, a, j = 0;
	for (i = 1; i <= n; i++)
	{
		creatnode(ht, i);
		printf("\n");	
	}
}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧