Huffman树和Huffman编码的概念在此不再赘述了。
实现Huffman树的难点在于如何从节点集合中找到两个权最小的节点并将其合并。
STL中的priority_queue基于小顶堆实现,能满足较快找到权重最小两节点的要求。
1.priority_queue的基本用法
首先对priority_queue的基本用法做简要介绍
#include <iostream>
#include <queue>
using namespace std;
struct Node
{
int n;
Node(int _n):n(_n){}
};
//自定义比较类
struct cmp
{
bool operator() (const Node &a, const Node &b)
{
return a.n > b.n;
}
};
int main()
{
//声明一个优先队列pq
priority_queue<Node, vector<Node>, cmp> pq;
Node n1(9);
Node n2(1);
Node n3(5);
Node n4(2);
//将元素依次插入优先队列pq
pq.push(n1);
pq.push(n2);
pq.push(n3);
pq.push(n4);
//输出队首元素,输出结果为1
cout << pq.top().n << endl;
//取出队首元素
pq.pop();
return 0;
}
2.实现Huffman编码
#include<iostream>
#include<cstdio>
#include<queue>
#include<deque>
using namespace std;
//字符结构体
struct Hcode
{
char ch;//字符
deque<int> huffcode;//字符的哈夫曼编码
};
//Huffman树节点
struct Hnode
{
int weight = 0;
Hnode *parent = NULL;
Hnode *Lchild = NULL;
Hnode *Rchild = NULL;
};
struct cmp
{
bool operator() (const Hnode *a, const Hnode *b)
{
return a->weight > b->weight;
}
};
//Huffman树构造函数
void huff_init(priority_queue<Hnode*, vector<Hnode*>, cmp>& pq, int n)
{
for(int i=0; i<n-1; i++)
{
if(pq.size() == 1)
break;
Hnode *Pnode = new Hnode();
Hnode *Lnode = pq.top();
pq.pop();
Hnode *Rnode = pq.top();
pq.pop();
Pnode->weight = Lnode->weight + Rnode->weight;
Pnode->Lchild = Lnode;
Pnode->Rchild = Rnode;
Lnode->parent = Pnode;
Rnode->parent = Pnode;
pq.push(Pnode);
}
}
//Huffman编码获取函数
/*获取Huffman编码的基本思想是从Huffman树的叶子节点出发,自底向上
* 若当前结点为父节点的左子树则在huffcode头部插入编码1,为左子树
* 则在huffcode头部插入编码0(01顺序不影响最优编码长度),直到根
* 节点,Huffman编码获取完成,从huffcode中顺序输出即可*/
void huff_code(Hnode *node, Hcode *code, int n)
{
for(int i=0; i<n; i++)
{
Hnode *currNode = &node[i];
for(;;)
{
if(currNode->parent == NULL)
break;
else
{
if(currNode->parent->Rchild == currNode)
{
code[i].huffcode.push_front(1);
}
else
{
code[i].huffcode.push_front(0);
}
}
currNode = currNode->parent;
}
}
}
//Huffman编码输出函数
void huff_print(Hcode *code, int n)
{
for(int i=0; i<n; i++)
{
printf("%c 's Huffman code is:",code[i].ch);
deque<int>::iterator it;
for(it = code[i].huffcode.begin(); it != code[i].huffcode.end(); it++)
cout << *it;
cout << endl;
}
}
int main()
{
int n;//字符数
scanf("%d",&n);
Hcode code[n];
Hnode node[n];
//依次读入字符频率
for(int i=0; i<n; i++)
scanf("%d",&node[i].weight);
fflush(stdin);
//依次读入字符
for(int i=0; i<n; i++)
scanf("%c",&code[i].ch);
//构造优先队列并初始化
priority_queue<Hnode*, vector<Hnode*>, cmp> pq;
for(int i=0; i<n; i++)
pq.push(node+i);
//构造Huffman树
huff_init(pq, n);
//获得Huffman编码
huff_code(node, code, n);
//输出Huffman编码
huff_print(code, n);
return 0;
}
3.输入输出样例
input:
6
45 13 12 16 9 5
ABCDEF
45 13 12 16 9 5
ABCDEF
output:
A 's Huffman code is:0
B 's Huffman code is:101
C 's Huffman code is:100
D 's Huffman code is:111
E 's Huffman code is:1101
F 's Huffman code is:1100
B 's Huffman code is:101
C 's Huffman code is:100
D 's Huffman code is:111
E 's Huffman code is:1101
F 's Huffman code is:1100