C++计算哈夫曼编码以及WPL

/*
手搓哈夫曼树计算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;
} 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值