04-树6. Huffman Codes--优先队列(堆)在哈夫曼树与哈夫曼编码上的应用
题目来源:http://www.patest.cn/contests/mooc-ds/04-%E6%A0%916
In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Redundancy Codes", and hence printed his name in the history of computer science. As a professor who gives the final exam problem on Huffman codes, I am encountering a big problem: the Huffman codes are NOT unique. For example, given a string "aaaxuaxz", we can observe that the frequencies of the characters 'a', 'x', 'u' and 'z' are 4, 2, 1 and 1, respectively. We may either encode the symbols as {'a'=0, 'x'=10, 'u'=110, 'z'=111}, or in another way as {'a'=1, 'x'=01, 'u'=001, 'z'=000}, both compress the string into 14 bits. Another set of code can be given as {'a'=0, 'x'=11, 'u'=100, 'z'=101}, but {'a'=0, 'x'=01, 'u'=011, 'z'=001} is NOT correct since "aaaxuaxz" and "aazuaxax" can both be decoded from the code 00001011001001. The students are submitting all kinds of codes, and I need a computer program to help me determine which ones are correct and which ones are not.
Input Specification:
Each input file contains one test case. For each case, the first line gives an integer N (2 <= N <= 63), then followed by a line that contains all the N distinct characters and their frequencies in the following format:
c[1] f[1] c[2] f[2] ... c[N] f[N]
where c[i] is a character chosen from {'0' - '9', 'a' - 'z', 'A' - 'Z', '_'}, and f[i] is the frequency of c[i] and is an integer no more than 1000. The next line gives a positive integer M (<=1000), then followed by M student submissions. Each student submission consists of N lines, each in the format:
c[i] code[i]
where c[i] is the i-th character and code[i] is a string of '0's and '1's.
Output Specification:
For each test case, print in each line either “Yes” if the student’s submission is correct, or “No” if not.
Sample Input:
7
A 1 B 1 C 1 D 3 E 3 F 6 G 6
4
A 00000
B 00001
C 0001
D 001
E 01
F 10
G 11
A 01010
B 01011
C 0100
D 011
E 10
F 11
G 00
A 000
B 001
C 010
D 011
E 100
F 101
G 110
A 00000
B 00001
C 0001
D 001
E 00
F 10
G 11
Sample Output:
Yes
Yes
No
No
题目大意:通过给定的字符及其访问次数,判断给定的编码是否为哈夫曼编码
判断条件:满足条件的编码形成的哈夫曼树可能不同,但其带权路径长度WPL一定相同且最小;且满足前缀码(前缀码是任何字符的编码都不是另一字符编码的前缀,前缀码可以避免二义性)
解题思路:
1.根据输入的节点(字符)以及权重(访问次数),模拟建立哈夫曼树,并求出其WPL
a.把权重建成一个最小堆(数组实现),然后每次弹出最小堆的最小元素即根节点
b.构造一个新的节点:从堆中依次弹出两个最小的元素的和作为新节点的权重,再将新节点插入堆中
c.WPL的值就是所有新节点的权重的和
2.根据输入的编码计算WPL用来判断是否与哈夫曼树的WPL相同
WPL等于每个字符编码访问次数与编码长度的乘积之和
3.根据输入的编码判断是否为前缀码
双重循环遍历,判断两个字符中某一个字符编码是否是另一个字符编码的前缀
图解建立哈夫曼树的过程中最小堆与哈夫曼树的变化如下:

代码如下:
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring> #define N 64 //最大字符数
#define M 200 //最大编码长度 int HuffmanWPL(int heap[]); /*模拟建立哈夫曼树,返回WPL*/
void PercolateDown(int heap[], int *Size, int parent); /*从节点parent开始下滤*/
void BuildMinHeap(int heap[], int *Size); /*通过传入的完全二叉树(数组)建立最小堆*/
int DeleteMin(int heap[], int *Size); /*删除堆中最小元素 */
void Insert(int minHeap[], int * Size, int weight); /*向最小堆中插入权重为weight的节点*/
int CountWPL(int f[], char code[][M]); /*计算一种编码的WPL*/
bool IsPrefixcode(char code[][M]); /*判断某种编码是否为前缀码*/
bool IsPrefix(char *s1, char *s2); /*判断两个字符中某一个字符编码是否是另一个字符编码的前缀*/ int n; //全局变量,字符的个数 int main()
{
char ch, code[N][M];
int f[N];
scanf("%d", &n);
for (int i = ; i <= n; i++) {
while(ch = getchar()) {
if (isalpha(ch) || isdigit(ch) || ch == '_') { //如果是字符
scanf("%d", &f[i]); //输出对应的访问次数
break;
}
}
}
int minWPL = HuffmanWPL(f); //通过模拟哈夫曼树得到最小WPL int stusNum; //学生个数(编码种类)
scanf("%d", &stusNum);
for (int i = ; i < stusNum; i++) {
for (int j = ; j <= n; j++) {
while(ch = getchar()) {
if (isalpha(ch) || isdigit(ch) || ch == '_') { //若为字符
scanf("%s", code[j]); //输入对应字符的编码
break;
}
}
}
int thisWPL = CountWPL(f, code);
if (thisWPL == minWPL && IsPrefixcode(code)) //若WPL为最小且为前缀码
printf("Yes\n");
else
printf("No\n");
}
return ;
} bool IsPrefixcode(char code[][M])
{
for (int i = ; i <= n; i++)
for (int j = i+; j <= n; j++)
if (IsPrefix(code[i], code[j]))
return false;
return true;
} bool IsPrefix(char *s1, char *s2)
{
while (s1 && s2 && *s1 == *s2) { //从编码首位向后遍历,当遍历到末端或两者不相等时退出循环
s1++;
s2++;
}
if (*s1 == '\0' || *s2 == '\0') //若遍历到某个字符编码的末端
return true; //则该字符是另一字符的前缀
else
return false;
} int CountWPL(int f[], char code[][M])
{
int WPL = ;
for (int i = ; i <= n; i++)
WPL += f[i] * strlen(code[i]); //权重*编码长
return WPL;
} void PercolateDown(int heap[], int *Size, int parent)
{
int temp = heap[parent];
int i, child; for (i = parent; i* <= (*Size); i = child){
child = * i;
if (child != (*Size) && heap[child+] < heap[child]) //找到值更小的儿子
child++;
if (temp > heap[child]) //如果值比下一层的大
heap[i] = heap[child]; //下滤
else
break;
}
heap[i] = temp;
} void BuildMinHeap(int heap[], int *Size)
{
for (int i = (*Size) / ; i > ; i--) //从最后一个有儿子的节点开始
PercolateDown(heap, Size, i); //向前构造最小堆
} int DeleteMin(int heap[], int *Size)
{
int minElem = heap[]; //最小堆根节点为最小值
heap[] = heap[*Size]; //将最小堆最后一个节点放到根节点处
(*Size)--; //节点数减一
PercolateDown(heap, Size, ); //从根节点开始下滤
return minElem;
} void Insert(int heap[], int * Size, int weight)
{
int i;
for (i = ++(*Size); i > && heap[i/] > weight; i /= ) //先将要插入的节点放最后
heap[i] = heap[i/]; //再上滤
heap[i] = weight;
} int HuffmanWPL(int heap[])
{
int minHeap[N];
int Size = ; for (int i = ; i < n; i++)
minHeap[Size++] = heap[i]; //将构造最小堆的数组初始化
minHeap[Size] = heap[n];
BuildMinHeap(minHeap, &Size); int WPL = ;
for (int i = ; i < n; i++) {
int leftWeight = DeleteMin(minHeap, &Size);
int rightWeight = DeleteMin(minHeap, &Size);
int rootWeight = leftWeight + rightWeight;
WPL += rootWeight;
Insert(minHeap, &Size, rootWeight);
}
return WPL;
}
04-树6. Huffman Codes--优先队列(堆)在哈夫曼树与哈夫曼编码上的应用的更多相关文章
- P3378 【模板】堆 (内含左偏树实现)
P3378 [模板]堆 题解 其实就是一个小根堆啦,STL就可以解决,但是拥有闲情雅致的我学习了Jelly_Goat的左偏树,增加了代码长度,妙啊 Solution 1 STL STL 里面prior ...
- 05-树9 Huffman Codes
哈夫曼树 Yes 需满足两个条件:1.HuffmanTree 结构不同,但WPL一定.子串WPL需一致 2.判断是否为前缀码 开始判断用的strstr函数,但其传值应为char *,不能用在strin ...
- 05-树9 Huffman Codes及基本操作
哈夫曼树与哈弗曼编码 哈夫曼树 带权路径长度(WPL):设二叉树有n个叶子结点,每个叶子结点带有权值 Wk,从根结点到每个叶子结点的长度为 Lk,则每个叶子结点的带权路径长度之和就是: WPL = 最 ...
- 哈夫曼树(C++优先队列的使用)
给定n个权值作为n个叶子结点,构造一棵二叉树,若带权路径长度达到最小,称为哈夫曼树(Huffman Tree).哈夫曼树是带权路径长度最短的树,权值较大的结点离根较近. 构造 假设有n个权 ...
- PTA 05-树9 Huffman Codes (30分)
题目地址 https://pta.patest.cn/pta/test/16/exam/4/question/671 5-9 Huffman Codes (30分) In 1953, David ...
- 数据结构慕课PTA 05-树9 Huffman Codes
题目内容 In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Re ...
- 【algo&ds】【吐血整理】4.树和二叉树、完全二叉树、满二叉树、二叉查找树、平衡二叉树、堆、哈夫曼树、B树、字典树、红黑树、跳表、散列表
本博客内容耗时4天整理,如果需要转载,请注明出处,谢谢. 1.树 1.1树的定义 在计算机科学中,树(英语:tree)是一种抽象数据类型(ADT)或是实作这种抽象数据类型的数据结构,用来模拟具有树状结 ...
- PAT 05-树8 Huffman Codes
以现在的生产力,是做不到一天一篇博客了.这题给我难得不行了,花了两天时间在PAT上还有测试点1没过,先写上吧.记录几个做题中的难点:1.本来比较WPL那块我是想用一个函数实现的,无奈我对传字符串数组无 ...
- 树-哈夫曼树(Huffman Tree)
概述 哈夫曼树:树的带权路径长度达到最小. 构造规则 1. 将w1.w2.-,wn看成是有n 棵树的森林(每棵树仅有一个结点): 2. 在森林中选出根结点的权值最小的两棵树进行合并,作为一棵新树的左. ...
随机推荐
- Windows 下在 Python (Anaconda) 中安装 Dlib 库
0. 引言 介绍在 Windows 操作系统下,在 Python 的 Anaconda 集成环境中,安装 Dlib 库 : 对于不了解源码编译的,或者利用 cmake 方法失败的,可以尝试下此方法: ...
- Linux建立互信关系(ssh公钥登录)
Linux有多种登录方式,比如telnet.ssh.支持ssh登录方式:口令登录和公钥登录 ssh登录方式:ssh [-l login_name] [-p port] [user@]hostname ...
- Laxcus大数据操作系统2.0(5)- 第二章 数据组织
第二章 数据组织 在数据的组织结构设计上,Laxcus严格遵循数据和数据描述分离的原则,这个理念与关系数据库完全一致.在此基础上,为了保证大规模数据存取和计算的需要,我们设计了大量新的数据处理技术.同 ...
- asp.net mvc access数据库操作
连接access数据库其实也简单,只要按照mvc的模式来就可以,遵循c v约定就可以 既然渲染试图是强类型,那么取得的数据就转换成强类型,其他一切和asp.net操作一样 DB mydb = new ...
- Centos7下安装Oracle11g r2
我的centos7是在virtualbox下安装的,安装Oracle安装了好久好久,最开始的时候在网上找的两个文章,按照步骤装,有一篇写着装的时候有灰色的竖线,直接按space键或者鼠标右键close ...
- python sys模块使用详情
python常用模块目录 sys模块提供了一系列有关Python运行环境的变量和函数.1.sys.argv可以用sys.argv获取当前正在执行的命令行参数的参数列表(list).变量解释sys.ar ...
- 过山车 HDU 2063 (二分图匹配裸题)
Problem Description RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了.可是,过山车的每一排只有两个座位,而且还有条不成文的规矩,就是每个女生必须找个个男生 ...
- Planning The Expedition(暴力枚举+map迭代器)
Description Natasha is planning an expedition to Mars for nn people. One of the important tasks is t ...
- java 队列的使用(转载)
转载声明:http://blog.csdn.net/lzy_lizhiyang/article/details/48311925 先我们要知道使用队列的目的是什么?一般情况下,如果是一些及时消息的处理 ...
- QList和QVector使用
版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:QList和QVector使用 本文地址:http://techieliang.com ...