#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<stack>
#include<queue>
#pragma warning(disable:4996)
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
class Node
{
private:
char character;
int weight;
int lchild, rchild;
string code;
public:
Node()
{
character = '\0';
weight = lchild = rchild = 0;
code = "";
}
Node(const char &ch, const int &w)
{
character = ch;
weight = w;
lchild = rchild = 0;
code = "";
}
Node(const int &w, const int &first, const int &second)
{
character = '\0';
weight = w;
lchild = std::min(first, second);
rchild = std::max(first, second);
code = "";
}
bool operator<(const Node&node)const
{
return weight > node.weight;
}
pair<map<char, string>, vector<Node>> HfCoding(const map<char, int>&char_freq)
{
priority_queue<Node>PQ;
vector<Node>tree(1);
for (auto iter = char_freq.begin(); iter != char_freq.end(); iter++)
{
PQ.push({ iter->first,iter->second });
}
while (PQ.size() > 1)
{
//从还没加入树的结点中找出两个权重最小的结点
auto first = PQ.top(); PQ.pop();
auto second = PQ.top(); PQ.pop();
Node parent;
parent.weight = first.weight + second.weight;
parent.lchild = tree.size();
parent.rchild = tree.size() + 1;
tree.push_back(first);
tree.push_back(second);
PQ.push(parent);
}
tree.push_back(PQ.top());
map<char, string>code;
queue<int>Q; Q.push(tree.size() - 1);
while (Q.size())
{
int i = Q.front();
Q.pop();
auto parent = tree[i];
if (parent.character)
{
code[parent.character] = parent.code;
}
if (parent.lchild)
{
tree[parent.lchild].code = tree[i].code + '0';
Q.push(parent.lchild);
}
if (parent.rchild)
{
tree[parent.rchild].code = tree[i].code + '1';
Q.push(parent.rchild);
}
}
return{ code,tree };
}
string Encoding(const string &text, map<char, string>&code)
{
string str;
for (size_t i = 0; i < text.size(); i++)
{
str += code[text[i]];
}
return str;
}
string Decoding(const string &code, const vector<Node>&tree)
{
string text;
for (size_t i = 0, parent = tree.size() - 1; i < code.size(); i++)
{
if (code[i] == '0')
{
parent = tree[parent].lchild;
}
else
{
parent = tree[parent].rchild;
}
if (tree[parent].character)
{
text+=tree[parent].character;
parent = tree.size() - 1;
}
}
return text;
}
};
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
string str;
while (getline(cin,str))
{
map<char, int>char_freq;
for (size_t i = 0; i < str.size(); i++)
{
char_freq[str[i]]++;
}
Node node;
auto code_tree = node.HfCoding(char_freq);
auto code = code_tree.first;
auto tree = code_tree.second;
auto HfCode = node.Encoding(str,code);
auto translation = node.Decoding(HfCode, tree);
}
return 0;
}
huffman
最新推荐文章于 2025-03-01 23:21:28 发布