霍夫曼(Huffman)编码

来源:百度知道 编辑:UC知道 时间:2024/05/15 09:06:47
【问题描述】
设计一算法实现对一组已知出现概率的符号进行霍夫曼(Huffman)编码。
【算法要求】
根据给定已知的符号及出现的概率,设计出霍夫曼树,并输出各个符号的编码。

/*
做huffman用堆排序应该效率最高了吧,不过自己写一个太麻烦,就直接用stl算了:
*/
#include <cstdio>
#include <vector>
#include <algorithm>

template< class Type >
struct node
{
node *left, *right;
int value;
const Type *data;
struct ptrcmp // 仿函数,用于堆排序的比较
{
bool operator () (const node* a, const node* b)
{
return a->value > b->value; // 最小堆
}
};
};

template< class Type >
node< Type >* buildHuffmanTree(const Type data[], int count)
{
typedef node< Type > Node;

// 初始化堆
::std::vector< Node* > heap(count, NULL);
heap.clear();
for(int i= 0; i < count; i++)
{
Node *n = new Node;
n->left = NULL;
n->right = NULL;
n->data = &data[i];
n->value = data[i]; // 如果Type不能转化到int,则必须重载一个operator int()
heap.push_back(n);
}
::std::make_