哈夫曼树

#include<bits/stdc++.h>
using namespace std;//哈夫曼树及其编码 
const int MAX=10;
const int MAXF=10000;

//哈夫曼树 
typedef struct{
	int weight;
	int lchild,rchild,parent;
}HFMtree;

//哈夫曼编码 
typedef struct{
	int weight;
	int data[MAX];
	int start;//start为哈夫曼编码初始位置 
}HFMcode;


//构建哈夫曼树a,用b储存哈夫曼编码,c为权值,n为结点数 
void HFMansf(HFMtree *(*a),HFMcode *(*b),int *c,int n)
{
	if(n<=1)
	return;
	int m=2*n-1;//结点总数 
	int xb1,xb2;
	int i,j;
	*a=new HFMtree [m];
	for(i=0;i<n;i++){
		(*a)[i].weight=c[i];
		(*a)[i].lchild=(*a)[i].rchild=(*a)[i].parent=-1;
	}//初始化叶子结点

	for(i=n;i<m;i++){
		(*a)[i].lchild=(*a)[i].rchild=(*a)[i].parent=-1;
	}
	int min1,min2; 
	for(i=n;i<m;i++){
		min1=min2=MAXF;
		for(j=0;j<i;j++){//找到两个权值最小的结点 
			if((*a+j)->parent==-1&&(*a+j)->weight<min1){
				min2=min1;xb2=xb1;min1=(*a+j)->weight;
				xb1=j;
			}
			else if((*a+j)->parent==-1&&(*a+j)->weight<min2){
				min2=(*a+j)->weight;xb2=j;
			}
		}
		(*a+xb1)->parent=(*a+xb2)->parent=i;
	    (*a+i)->weight=min1+min2; 
		(*a+i)->lchild=xb1;(*a+i)->rchild=xb2;
	}
	*b=new HFMcode [n];
	int start;
	int f,d;
	for(i=0;i<n;i++){
		f=(*a+i)->parent;
		(*b+i)->weight=c[i];
		d=i;
		start=n;
		while(f!=-1){
		    if((*a+f)->lchild==d)
			(*b+i)->data[--start]=0;
		    else 
		    (*b+i)->data[--start]=1;
		    d=f;f=(*a+d)->parent;
		}
		(*b+i)->start=start;
	}

} 
 
int main()
{
	HFMcode *b;HFMtree *a;int n=6;
	int c[]={7,8,4,3,2,6};
	HFMansf(&a,&b,c,n);
	int i,j;
	for(i=0;i<n;i++)
	{
		cout<<"权值:"<<(b+i)->weight<<'\n'<<"编码:";
		for(j=(b+i)->start;j<n;j++)
		cout<<(b+i)->data[j];
		cout<<endl;
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦西空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值