<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; }
相关文章推荐
- SDWebImage原理和使用
- [AngularJS面面观] 5. scope中的两个异步方法 - $applyAsync以及$evalAsync
- MySQL提示:The server quit without updating PID file问题的解决办法
- Android Bitmap深入介绍(一)---基础
- 如果觉得职业看不到头,趁早换工作吧
- Gulp实现前端搭建
- 桜の花びらたち歌词
- Cookie知识点小结
- php 超时 解决办法 (Maximum execution time of 30 seconds exceeded)这个问题?
- windows安装theano
- Linux下python版本的更新以及第三方包的安装
- Nginx和Apache比较
- CodeForces 667A Pouring Rain
- Android第一行代码源码分享
- ssh
- Android快速开发最常用的工具类集锦--好东西在精不在多
- 廖雪锋笔记2:字符串和编码
- 综合日语第一册第十五课
- HttpConnect与HttpClient基本用法
- struts 中继承ActionSupport类