哈夫曼编码

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

struct HuffmanTree {
	char val;
	int weight;
	struct HuffmanTree* left;
	struct HuffmanTree* right;
};
//虚函数
class condition {
public:
	bool operator()(HuffmanTree* H1, HuffmanTree* H2)
	{
		return H1->weight < H2->weight;
	}
};

void CreatHuffmanTree(vector<int>v,HuffmanTree** root)
{
	vector<HuffmanTree*>Tree;
	for (int i = 0; i < v.size(); i++)
	{
		if (v[i] > 0)
		{
			HuffmanTree* temp = new HuffmanTree();
			temp->weight = v[i];
			temp->val = 'a' + i;
			temp->left = NULL;
			temp->right = NULL;
			Tree.push_back(temp);
		}
	}
	while (Tree.size() > 1)
	{
		sort(Tree.begin(), Tree.end(), condition());
		HuffmanTree* temp = new HuffmanTree();
		temp->weight = Tree[0]->weight + Tree[1]->weight;
		temp->left = Tree[0];
		temp->right = Tree[1];
		Tree[1] = temp;
		Tree.erase(Tree.begin());
	}
	*root =  Tree[0];
}

void HuffmanCode(HuffmanTree* root, int depth,vector<int>code)
{
	if (root)
	{
		if (root->left == NULL && root->right == NULL)
		{
			cout << root->val << ": ";
			for (int i = 0; i < depth; i++)
			{
				cout << code[i];
			}
			cout << endl;
		}
		else
		{
			code.push_back(0);
			HuffmanCode(root->left, depth + 1, code);
			code.pop_back();
			code.push_back(1);
			HuffmanCode(root->right, depth + 1, code);
		}
	}
}

string HuffmanDecode(HuffmanTree* root, string str)
{
	string ret;
	HuffmanTree* temp = NULL;
	int i = 0;
	while (i < str.size())
	{
		temp = root;
		while (temp->left != NULL && temp->right != NULL)
		{
			if (str[i] == '0')
				temp = temp->left;
			else
				temp = temp->right;
			i++;
		}
		ret.push_back(temp->val);
	}
	return ret;
}
int main()
{
	string str;
	HuffmanTree* root;
	cout << "请输入编码字符串:" << endl;
	cin >> str;
	vector<int>v(26);
	for (int i = 0; i < str.size(); i++)
	{
		v[str[i] - 'a']++;
	}
	//创建哈夫曼树
	CreatHuffmanTree(v,&root);

	//哈夫曼编码
	vector<int>code;
	HuffmanCode(root, 0,code);

	//哈夫曼解码
 	cout << "请输入码字:" << endl;
	cin >> str;
	string ret;
	ret = HuffmanDecode(root, str);
	cout << "解码结果为:" << endl;
	cout << ret << endl;
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值