算法导论贪心算法——哈夫曼编码

不具体介绍了,只给出我的代码和结果,可能代码有些部分不是很规范,有空再修改下。改了能有4个小时。。好开心,哈哈哈

#include<iostream>
#include<string>
using namespace std;

int maxsize=100;

struct huffmannode {
	int weight;
	char a;
	huffmannode* leftchild;
	huffmannode* rightchild;
	huffmannode(){}
	huffmannode(huffmannode* aa, huffmannode* bb, int num, char el):leftchild(aa), rightchild(bb), weight(num), a(el) {
	}
};

struct input{
	int weight;
	char a;
};

void bubblesort(huffmannode *aa, int begin, int asize) { //按照权值从小到大排序
	for(int i=begin;i<asize;i++) {
		for(int j=begin;j<asize-i-1+begin;j++) {
			if(aa[j].weight>aa[j+1].weight) {
				huffmannode c;
				c=aa[j];
				aa[j]=aa[j+1];
				aa[j+1]=c;
			}
		}
	}
}

huffmannode* createhuffmantree(input *aa, int asize) {
	huffmannode* huffmantree=new huffmannode[maxsize];
	//huffmannode* huffmantree[100];
	if(asize==0) return nullptr;//空树
	else if(asize==1) {//只有一个节点
		huffmannode* res;
		res->a=aa[0].a;
		res->weight=aa[0].weight;
		res->leftchild=nullptr;
		res->rightchild=nullptr;
		return res;
	}
	else {//树有多个节点	
		for(int i=0;i<asize;i++) {
			huffmannode *re=new huffmannode(nullptr, nullptr, aa[i].weight, aa[i].a);
			huffmantree[i].a=re->a;
			huffmantree[i].weight=re->weight;
			huffmantree[i].leftchild=nullptr;
			huffmantree[i].rightchild=nullptr;
		}
		for(int i=0;i<asize-1;) {
			bubblesort(huffmantree, i, asize);
			huffmannode *re=new huffmannode(&huffmantree[i], &huffmantree[i+1], (huffmantree[i].weight+huffmantree[i+1].weight), '0');
			asize++;
			huffmantree[asize-1]=*re;
			i=i+2;
		}
	}
	return &huffmantree[asize-1];
}

void print(huffmannode* res) {
	if(res==nullptr) return ;
	if(res!=nullptr) {
		cout<<"当前结点:"<<res->weight<<" "<<res->a<<".";
		if(res->leftchild)
			cout<<"它的左孩子:"<<res->leftchild->weight<<" "<<res->leftchild->a<<".";
		else
			cout<<"无左孩子.";
		if(res->rightchild)
			cout<<"它的右孩子:"<<res->rightchild->weight<<" "<<res->rightchild->a<<".";
		else
			cout<<"无右孩子.";
		cout<<endl;
		print(res->leftchild);
		print(res->rightchild);
	}
	return ;
}

int main() {
	int n;
	cout<<"输入节点个数:";
	cin>>n;
	input *aa=new input[n];
	for(int i=0;i<n;i++) {
		cout<<"输入第"<<i+1<<"个字母:";
		cin>>aa[i].a;
		cout<<"输入第"<<i+1<<"个字母的权值:";
		cin>>aa[i].weight;
	}
	huffmannode* res=createhuffmantree(aa, n);
	print(res);
	delete []aa;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值