/*
手搓哈夫曼树计算WPL以及各个字母的哈夫曼编码
*/
#include <iostream>
#include <unordered_map>
#include <queue>
using namespace std;
int WPL;
typedef struct BNode{
int freq;
char alp;
string huff_code;
BNode *left;
BNode *right;
BNode(char c, int x){
freq = x;
alp = c;
huff_code = "";
left = right = nullptr;
}
}BNode, *BTree;
struct cmp{
bool operator()(BNode *&a,BNode *&b)
{
if(a->freq != b->freq)
return a->freq > b->freq;
else
return a->alp > b->alp;
}
};
BTree build_huffman(unordered_map<char,int> Hash)
{
priority_queue<BNode*,vector<BNode*>,cmp> Heap;
for(auto it : Hash)
{
BNode *node = new BNode(it.first,it.second);
Heap.push(node);
}
while(Heap.size() != 1)
{
auto a = Heap.top(); Heap.pop();
auto b = Heap.top(); Heap.pop();
BNode* c = new BNode(' ',a->freq + b->freq);
c->left = a;
c->right = b;
Heap.push(c);
}
return Heap.top();
}
void traversal(BTree root,string huff,int height)
{
if(!root) return ;
if(!root->left && !root->right) // 叶子节点
{
WPL += (root->freq) * height;
root->huff_code = huff;
cout << root->alp << " " << root->freq << " " << root->huff_code << endl;
}
traversal(root->left,huff + "0",height + 1);
traversal(root->right,huff + "1",height + 1);
}
int main()
{
unordered_map<char,int> Hash;
Hash['a'] = 1;
Hash['b'] = 2;
Hash['c'] = 2;
Hash['d'] = 5;
Hash['e'] = 9;
BTree root = build_huffman(Hash);
traversal(root,"",0);
cout << "WPL = " << WPL << endl;
return 0;
}
C++计算哈夫曼编码以及WPL
最新推荐文章于 2024-09-01 16:42:17 发布