问题描述:
使用贪心算法求解Huffman编码问题,具体来说就是,根据每个字符的出现频率,使用最小堆构造最小优先队列,构造出字符的最优二进制表示,即前缀码。
【输入形式】在屏幕上输入字符个数和每个字符的频率。
【输出形式】每个字符的Huffman编码。字符从a开始,依次为b, c, ...
样例输入:
6 45 13 12 16 9 5
【样例输出】
a 0 b 101 c 100 d 111 e 1101 f 1100
【样例说明】
输入:字符个数为6,a至f每个字符的频率分别为:45, 13, 12, 16, 9, 5。
输出:a至f每个字符对应的Huffman编码。
说明:为了保证每个字符对应的Huffman编码的唯一性,对于所有测试样例,得到的Huffman编码树中,对于任何一个除叶结点以外的结点,其左儿子结点的频率小于其右儿子结点的频率(两者不会相等)。
c++代码
#include <iostream>
#include <queue>
#include <vector>
#include <map>
using namespace std;
struct node {
char ch;
int w;
int flag;
string s;
node *left;
node *right;
node(char c, int weight, int f) : ch(c), w(weight), flag(f), s(""),left(nullptr), right(nullptr) {}
bool operator>(const node &b) const {
return this->w > b.w;