Huffman coding哈夫曼编码

Description

In computer science and information theory, a Huffman code is an optimal prefix code algorithm.

In this exercise, please use Huffman coding to encode a given data.

You should output the number of bits, denoted as B(T), to encode the data:

B(T)=∑f(c)dT(c),

where f(c) is the frequency of character c, and dT(c) is be the depth of character c's leaf in the tree T.

Input

The first line is the number of characters n.

The following n lines, each line gives the character c and its frequency f(c).

Output

 Output a single number B(T).

题目解释:对给出的节点构建哈夫曼树

输入:第一行表示有节点数n,后面n行表示n个节点,每一个节点(也就是每一行)使用节点号和出现频率来表示

输出:B(T) = f(c)d(c)总和(f(c)表示节点c的频率,d(c)表示节点c在哈弗曼树中的深度)

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

struct HuffmanNode{     //构建哈夫曼节点
    char character;
    int frequency;
    HuffmanNode *lchild,*rchild;
    HuffmanNode():character(0),frequency(0),lchild(NULL),rchild(NULL){}
};
typedef HuffmanNode *HTNode;

struct cmp{          //重定义排序
    bool operator()(HuffmanNode *a,HuffmanNode *b)
    {
        return a->frequency > b->frequency;
    }
};
int main()
{
    int n;
    priority_queue<HTNode,vector<HTNode>,cmp> pq;    //使用priority_queue进行节点存储,能够及时排序
    while( cin >> n)
    {
        for(int i = 0; i < n; i++)
        {
            HTNode tmpNode = new HuffmanNode;       //对节点进行存储
            cin >> tmpNode->character >> tmpNode->frequency;
            pq.push(tmpNode);
        }
        int BT = 0;
        while(pq.size()>1)
        {
            HTNode tmp1 = new HuffmanNode;  //获得频率最小的两个节点进行合并
            tmp1 = pq.top();
            pq.pop();
            HTNode tmp2 = new HuffmanNode;
            tmp2 = pq.top();
            pq.pop();
            HTNode tmp = new HuffmanNode;
            tmp->frequency = tmp1->frequency +tmp2->frequency;
            tmp->lchild = tmp1;
            tmp->rchild = tmp2;
            BT +=  tmp1->frequency + tmp2->frequency;
            pq.push(tmp);                 //每一次对priority_queue进行操作都会自动更新排序
        }
        cout << BT << endl;
    }
    return 0;
}                                 

后记:

1.priority_queue能够及时对节点进行排序,可以最快地获得更新后的最小两个节点,实现新的更新


代码新手,欢迎各位大神提出宝贵的意见和建议

你可能感兴趣的:(算法,sicily)