一、题目描述

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[n];
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;
}

最新文章

  1. Sublime Text编辑器的12个技巧和诀窍
  2. 关于delphi点击webbrowser中任意一点的问题
  3. Asp.net MVC的Model Binder工作流程以及扩展方法(1) - Custom Model Binder
  4. Android Studio中提示:Project SDK is not defined
  5. C# 实现 单例模式
  6. Python 主要模块和常用方法简览
  7. R 中安装xlsx包缺少java环境解决方案
  8. [Guava源码分析]Ordering:排序
  9. C#中实现抽象类里建立静态方法
  10. RHEL5.8安装Oracle11g
  11. sqlserver生成随机数 2011-12-21 15:47 QQ空间
  12. 其他应用和技巧-用try和catch来让程序更友好
  13. C#获取本周第一天和最后一天
  14. Deploy Mysql
  15. [LeetCode] Minimum Genetic Mutation 最小基因变化
  16. zabbix利用orabbix监控oracle
  17. technologies
  18. 微信小程序-if条件渲染
  19. Ping IP速度范围
  20. pyc文件

热门文章

  1. IOS 数据存储之 SQLite具体解释
  2. bzoj1830: [AHOI2008]Y型项链(LCP+贪心)
  3. m_Orchestrate learning system---三、session使用完整流程是什么
  4. [JZOJ 5911] [NOIP2018模拟10.18] Travel 解题报告 (期望+树形DP)
  5. 利用canvas做一个简单个gif停止和播放
  6. 线程状态与tcb、线程的生命周期
  7. ActiveMQ学习笔记(15)----Message Dispatch高级特性(一)
  8. 壹、js的概述
  9. NOIp2018模拟赛四十
  10. Python中编写精美图形界面(PyQt5)