贪心法求解哈夫曼编码问题

#include<iostream>
#include<queue>
#include<vector>
#include<string>
#include<map>
using namespace std;
#define MAX 101
int n;
struct HTreeNode{
	char data;
	int weight;
	int parent;
	int lchild,rchild;
};
HTreeNode ht[MAX];
map<char,string> htcode;
struct NodeType{
	int no;
	char data;
	int weight;
	bool operator < (const NodeType &s) const{
		return s.weight<weight;
	}
};
void CreateHTree(){
	NodeType e,e1,e2;
	priority_queue<NodeType>qu;
	for(int k=0;k<2*n-1;k++){
		ht[k].lchild=ht[k].rchild=ht[k].parent=-1;
	}
	for(int i=0;i<n;i++){
		e.no=i;
		e.data=ht[i].data;
		e.weight=ht[i].weight;
		qu.push(e);
	}
	for(int j=n;j<2*n-1;j++){
		e1=qu.top();qu.pop();
		e2=qu.top();qu.pop();
		ht[j].weight=e1.weight+e2.weight;
		ht[j].lchild=e1.no;
		ht[j].rchild=e2.no;
		ht[e1.no].parent=j;
		ht[e2.no].parent=j;
		e.no=j;
		e.weight=e1.weight+e2.weight;
		qu.push(e);
	}
}
void CreateHCnode(){
	string code;
	code.reserve(MAX);
	for(int i=0;i<n;i++){
		code="";
		int curno=i;
		int f=ht[curno].parent;
		while(f!=-1){
			if(ht[f].lchild==curno) code='0'+code;
			else code='1'+code;
		}
		htcode[ht[i].data]=code;
	}
}
void DispHCnode(){
	map<char,string>::iterator it;
	for(it=htcode.begin();it!=htcode.end();it++){
		cout<<" "<<it->first<<":"<<it->second<<endl;
	}
}
void DispHTree(){
	for(int i=0;i<2*n-1;i++){
		printf("data=%c,weight=%d,lchild=%d,rchild=%d,parent=%d",
		ht[i].data,ht[i].weight,ht[i].lchild,ht[i].rchild,ht[i].parent);
	}
}
int WPL(){
	int wps=0;
	for(int i=0;i<n;i++){
		wps+=ht[i].weight*htcode[ht[i].data].size();
	}
} 
int main(){
	n=5;
	ht[0].data='a';ht[0].weight=4;
	ht[0].data='a';ht[0].weight=4;
	ht[0].data='a';ht[0].weight=4;
	ht[0].data='a';ht[0].weight=4;
	ht[0].data='a';ht[0].weight=4;
	CreateHTree();
	DispHTree();
	CreateHCnode();
	DispHCnode();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值