您的位置:首页 > 其它

<Sicily>Huffman coding

2016-06-08 00:33 323 查看

一、题目描述

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.

二、输入

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 a single number B(T).

例如:

输入:

5

0 5

1 4

2 6

3 2

4 3

输出:

45

四、解题思路

1、所有的节点存放在一个数组中

2、对数组按每个节点的权值从小到大进行排序

本文使用快速排序

3、取出权值最小的两个节点,生成新的节点,原来的两个节点分别为新的节点的左右子树,新节点的权值为原来两个节点的权值之和

4、把新的节点按照权值插入到已经有序的数组中

5、重复步骤3、4,直到只剩根节点

五、代码

#include<iostream>
#include<string>
#include <vector>

using namespace std;

//节点结构
struct Node{
char ch;
int weight;
Node *leftChild, *rightChild;
};

//插入排序
void insertSort(Node** nodeArray, int low, int high)
{
for(int i = low + 1; i < high; i++)
{
Node* temp = nodeArray[i];
int j = i - 1;
while(j >= low && nodeArray[j]->weight > temp->weight)
{
nodeArray[j+1] = nodeArray[j];
j--;
}
nodeArray[j+1] = temp;
}
}

//建Hffman树
void createHuffman(Node** nodeArray, int n)
{

insertSort(nodeArray, 0, n);    //先对节点按weight排序
int p = 0;
int res = 0;
while(p < n - 1)
{
Node* minNode1 = nodeArray[p];  //找出weight值最小的两个
Node* minNode2 = nodeArray[++p];
Node* newNode = new Node;
newNode->weight = minNode1->weight + minNode2->weight;  //合并生成新的节点
res += newNode->weight;

newNode->leftChild = minNode1;
newNode->rightChild = minNode2;
nodeArray[p] = newNode;
insertSort(nodeArray, p, n);
}

cout << res <<endl;
}

int main()
{
int n;
cin >> n;
char ch;
int weight;
Node* nodeArray
;
for(int i = 0; i < n; i++)
{
Node* node = new Node;
cin >> ch >> weight;
node->ch = ch;
node->weight = weight;
nodeArray[i] = node;
}
createHuffman(nodeArray, n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: