#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;
}
哈夫曼编码
最新推荐文章于 2024-11-02 09:55:19 发布