Huffman Codes

article/2025/9/29 1:16:12

题目

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 an non-empty string of no more than 63 '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.
Note: The optimal solution is not necessarily generated by Huffman algorithm. Any prefix code with code
length being optimal is considered correct.

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

解题思路

1.首先要明白题意,题目中说哈夫曼算法可以得到最优编码,但是最优编码不一定通过哈夫曼算法得到,也就是说最优编码可能不唯一,哈夫曼算法得到的只是其中一种。

2.哈夫曼编码的特点:

1.最优编码——总长度(WPL)最小
2.无歧义解码——前缀码:数据仅存于叶子节点
3.没有度为1的结点——满足前两条一定有第三条:可以用反证法,如果有一个结点的度为1,那么这个结点就不是编码的结点,而这个度为1的结点肯定可以去掉,就不满足1了。

3.要判断提交的哈夫曼编码是否正确,就要判断通过提交的哈夫曼编码建的树是否符合哈夫曼编码的特点1和2。

4.判断特点1或2,都需要建树来检查是否符合,我们通过哈夫曼算法的到最小WPL和建完树的WPL比较。建树这一步,我考虑可不可以通过判断两棵树是否同构来判断是否是最优编码,但是即使不同构也可能是最优编码,所以不能这么判断。

代码:

#include <iostream>
#include <queue>
#include <string>
#include <vector>#define MinData -1
#define MAXSIZE 1001using namespace std;using HuffmanTree =class TreeNode*;
class TreeNode {
private:int Weight=0;   //权重HuffmanTree Left=nullptr;HuffmanTree Right=nullptr;public:friend class MinHeap;int WPL(int Depth);   //用来计算最优编码长度,H是深度bool is_suc_BuildHT(string Code, vector<int> Weight_,int index);    //用来将读入的编码转换成树,判断是否成功
};class MinHeap {
private:HuffmanTree Elements[MAXSIZE];       //存储堆元素的数组int Size;           //堆的当前元素个数int Capacity;      //堆的最大容量,这里是指存入的结点数public:MinHeap(int MaxSize);HuffmanTree Huffman();       //构造哈夫曼树void AddData(vector<int> Weight_);  //先按完全二叉树加入数据HuffmanTree Delete();   //取出堆顶void PercDown(int Root);         //下滤函数void BuildMinHeap();               //按权重调整函数void Insert(HuffmanTree item);     //插入元素 
};int main()
{HuffmanTree T;           //为了求最小WPL而建的树int Num_of_Node, Num_of_test;    //结点数,检查的个数vector<int> Weight;  //存放权重值int CodeLen;    //最优WPLqueue<int> Q;  //用来存放判断的结果  int count = 0;  //为了结尾输出没有换行符cin >> Num_of_Node;       //输入结点数MinHeap H{ Num_of_Node };   //建立堆Hchar c_;int weight_;for (int i = 0; i < Num_of_Node; i++) {    //将权重值读入到数组中cin >> c_ >> weight_;Weight.push_back(weight_);}H.AddData(Weight);   //加入数据,按照完全二叉树H.BuildMinHeap();    //按权值将堆调整为最小堆T=H.Huffman();  //生成哈夫曼树CodeLen = T->WPL(0);  //求最小WPLcin >> Num_of_test;   //读入要测试的数量for (int i = 0; i < Num_of_test; i++) {int flag = 1;char C;string Code;HuffmanTree HT=new TreeNode;   //根据编码构建的树for (int j = 0; j < Num_of_Node; j++) {     //测试编码cin >> C >> Code;if (Code.length() > Num_of_Node - 1) flag = 0;   //长度不符合if (flag && !HT->is_suc_BuildHT(Code, Weight, j)) flag = 0;    //长度符合了就建树}if (flag&& (HT->WPL(0) == CodeLen)) Q.push(true);  //判断树是否建成,建成是否符合前缀码规范,符合了就再判断WPLelse  Q.push(false); //否则直接判断不是delete HT;}while (!Q.empty()) {if (Q.front()) cout << "Yes";else cout << "No";Q.pop();count++;if (count != Num_of_test) cout << endl;}return 0;
}bool TreeNode::is_suc_BuildHT(string Code, vector<int> Weight_, int index) {int i = 0;if (i < Code.length()) {if (Code[i] == '0') {if (Left == nullptr) {HuffmanTree T = new TreeNode;T->Weight = Weight_[index];Left = T;if (Code.length() == 1) return true; }if (Code.length() == 1) return false;else return Left->is_suc_BuildHT(Code.substr(i + 1), Weight_, index);}else if (Code[i] == '1') {if (Right == nullptr) {HuffmanTree T = new TreeNode;T->Weight = Weight_[index];Right = T;if (Code.length() == 1) return true;}if (Code.length() == 1) return false;else return Right->is_suc_BuildHT(Code.substr(i + 1), Weight_, index);}}  
}int TreeNode::WPL(int Depth) {if (Left == nullptr && Right == nullptr)return Depth * Weight;else if (Left && Right) return Left->WPL(Depth + 1) + Right->WPL(Depth + 1);else return -1000;  //在上一步建树的时候,可能会有树不符合哈夫曼树的特点3
}HuffmanTree MinHeap::Huffman(){    //假设H->Capacity个权重值已经存放在H->Element[]->WeightHuffmanTree T;for (int i = 1; i < Capacity; i++){T = new TreeNode;T->Left = Delete();T->Right = Delete();T->Weight = T->Left->Weight + T->Right->Weight;Insert(T);     //将T插入最小堆}T = Delete();return T;
}MinHeap::MinHeap(int MaxSize) {Size = MaxSize;Capacity = MaxSize;HuffmanTree Node = new TreeNode;Node->Weight = MinData;             //定义哨兵为堆中所有元素的最小值Elements[0] = Node;
}void MinHeap::AddData(vector<int> Weight_) {for (int i = 0; i < Capacity; i++) {HuffmanTree Node = new TreeNode;Node->Weight = Weight_[i];Elements[i + 1] = Node;}
}HuffmanTree MinHeap::Delete(){int Parent, child;HuffmanTree MinItem, temp;/*有需要可以插入判断堆是否为空*/MinItem = Elements[1];temp = Elements[Size--];for (Parent = 1; Parent * 2 <= Size; Parent = child){child = Parent * 2;if ((child < Size) && \(Elements[child]->Weight > Elements[child + 1]->Weight))child++;if (temp->Weight <= Elements[child]->Weight) break;elseElements[Parent] = Elements[child];}Elements[Parent] = temp;return MinItem;
}void MinHeap::PercDown(int Root){ /* 下滤:将H中以Elements[p]为根的子堆调整为最小堆 */int Parent, Child;HuffmanTree X;X = Elements[Root]; /* 取出根结点存放的值 */for (Parent = Root; Parent * 2 <= Size; Parent = Child) {Child = Parent * 2;if ((Child != Size) && (Elements[Child]->Weight > Elements[Child + 1]->Weight))Child++;  /* Child指向左右子结点的较小者 */if (X->Weight <= Elements[Child]->Weight) break; /* 找到了合适位置 */else  /* 下滤X */Elements[Parent] = Elements[Child];}Elements[Parent] = X;
}void MinHeap::BuildMinHeap(){ /* 调整Elements[]中的元素,使满足最小堆的有序性  *//* 这里假设所有H->Size个元素已经存在Elements[]中 */int i;/* 从最后一个结点的父节点开始,到根结点1 */for (i = Size / 2; i > 0; i--)PercDown(i);
}void MinHeap::Insert(HuffmanTree item){int i;/*有需要可以判断堆是否已满*/i = ++Size;    //指向堆最后一个元素的位置for (; Elements[i / 2]->Weight > item->Weight; i /= 2) {      //哨兵解决了插入的结点是所有结点最小的情况Elements[i] = Elements[i / 2];}Elements[i] = item;
}

运行结果:

在这里插入图片描述


http://chatgpt.dhexx.cn/article/YFma36mu.shtml

相关文章

HuffmanTree

#include "stdafx.h" #include "stdio.h" #include "stdlib.h" #include "string.h"typedef int ELEMTYPE;//哈弗曼树节点结构体 typedef struct HuffmanTree {ELEMTYPE weight;ELEMTYPE id;//区分权值相同的节点struct HuffmanTree* …

JPEG中Huffman解码实例讲解

DHT Huffuman表格式 -------------------------------------------------------------------------- 名称 字节数 值 说明 -------------------------------------------------------------------------- 段标识 1 FF 段类型 1 C4 段…

哈夫曼树(huffman)

学完了huffman树&#xff0c;讲一下自己对它的理解 huffman树遵循二叉树的原则&#xff0c;每个节点最多有两个子节点&#xff0c;但是每个节点都带有一个权重&#xff0c;如果我们要将一组字符串 “ B D C A F E ” 插入huffman树&#xff0c;每个字符都会带有一个权重&#…

Huffman树和Huffman编码

文章目录 Huffman树的定义带权路径长度WPL Huffman树的构造Huffman树的特点 Huffman编码构造Huffman编码 Huffman树的定义 哈夫曼&#xff08;Huffman&#xff09;树&#xff0c;又称最优二叉树&#xff0c;是一类带权路径长度WPL最短的树。 带权路径长度WPL 要理解带权路径…

Huffman树(哈夫曼树)

哈夫曼树又称最优二叉树&#xff0c;是一种带权路径长度最短的二叉树。所谓树的带权路径长度&#xff0c;就是树中所有的叶结点的权值乘上其到根结点的路径长度&#xff08;若根结点为0层&#xff0c;叶结点到根结点的路径长度为叶结点的层数&#xff09;。树的带权路径长度记为…

虚拟机下安装BackTrack5 (BT5)教程及BT5汉化

isare邀请您访问Backtrack中文网 http://www.backtrack.org.cn/?fromuid50397 isare邀请您访问Backtrack中文网 http://www.backtrack.org.cn/?fromuserisare PS&#xff1a;back track 安装过程中有2点要注意&#xff1a;第一&#xff1a;复制到99%的时候会等大约10来分钟&a…

bt 下载工具 deluge 配置 优化 使用

目录 Ubuntu 18 配置 deluge Deluge 安卓远程客户端 Deluge 性能调优 deluge是基于libtorrentpython的跨平台bt/pt客户端&#xff0c;适合在Linux环境下使用 deluge完全开源免费&#xff0c;对IPv6支持良好&#xff0c;性能优于transmission&#xff1b;在嵌入式设备上使用d…

BT5的U盘完整安装

BT5是什么就不用多说了&#xff0c;从网上看了许多教程&#xff0c;大多是利用unetbootin工具将ISO文件直接解压到U盘上&#xff0c;这样并不能完全使用BT&#xff0c;保存好的文件&#xff0c;重启机器后就没了&#xff0c;其实就是当做光盘使用了&#xff0c;另外还有一个方法…

有哪些好用的BT下载器?

​​​​​​2022年5个好用的 BT/ 磁力链接下载工具推荐 &#xff5c;Windows 、安卓系统 | 科技雷达 A full-featured download manager

BT是如何下载的

BT协议简介 一、BT下载是怎么来的&#xff1f; 在互联网上下载文件的方式大概有这么几种&#xff1a;FTP、HTTP、BT、eMule(电驴)等&#xff0c; 浏览器会直接支持FTP和HTTP下载&#xff0c;BT和eMule下载一般需要专用的下载软件的支持。 接下来分别简单介绍一下他们的区别&…

ed2k下载

ed2k下载 在下载ed2k资源的时候&#xff0c;浏览器一般不能直接下载&#xff0c;这个时候该怎么办呢&#xff1f; 方法一&#xff1a;下载迅雷&#xff0c;直接安装 方法二&#xff1a;使用在线工具&#xff0c;将链接转化为别的形式 https://tool.lu/urlconvert/ 方法三&am…

BT是怎么下载的

BT协议简介 一、BT下载是怎么来的? 在互联网上下载文件的方式大概有这么几种:FTP、HTTP、BT、eMule(电驴)等, 浏览器会直接支持FTP和HTTP下载,BT和eMule下载一般需要专用的下载软件的支持。 接下来分别简单介绍一下他们的区别: FTP 是 File Transfer Protocol(文件…

最好用的bt下载器qbittorrent下载安装使用教程

qBittorrent绝对是我心目中BT下载工具中的NO.1&#xff0c;虽说我平时也会用迅雷下载国内的某些资源&#xff0c;但是仍然不妨碍它是我心目中的主力下载神器&#xff01;它可以说是我最早接触的除迅雷之外的一款BT下载神器。它是完全免费的种子和磁力链接下载工具&#xff0c;最…

BT5 WIFI破解

实验环境 VMwareWorkstation 9.0 BackTrack5 R3-GNOME-32 工具说明 VMware&#xff1a;著名的虚拟机软件&#xff0c;本实验采用虚拟机环境下安装BackTrack。 BackTrack&#xff1a;是一个基于Ubuntu GNU/Linux的发行版本&#xff0c;主要用做数字取证和入侵测试。其无线安全审…

BT5下载地址

http://www.backtrack-linux.org/downloads/ 下载方法&#xff1a; 1,先填写好网页里的三个框,如: Your Name(你的名字): ABC Email Address(邮箱): ABC163.com Country(国家): china 2,然后点"download" 3,按照自己的…

最全BT介绍

BitTorrent 简介 riba2534 2021年04月11日 19:26 阅读 851 关注 BitTorrent 简介 从 P2P 说起 经常在网上飙车的老司机应该都知道 BT 下载&#xff0c;但是有时候拿到了种子却下载不动&#xff0c;会不会很抓狂&#xff0c;是不是还觉得是自己网不行&#xff0c;那作为一…

034_Unicode标准

1. Unicode标准 1.1. 由于ASCII字符集、ISO字符集、GBK字符集列出的字符集都有容量限制, 而且不兼容多语言环境, Unicode联盟开发了Unicode标准。 1.2. Unicode标准涵盖了世界上的所有字符、标点和符号。 1.3. 不论是何种平台、程序或语言, Unicode都能够进行文本数据的处理…

24.字符编码

1.字符编码 1.1简介 字符编码只与文本文件和字符串有关。 字符编码&#xff1a;记录人类字符与二进制数的对应关系。计算机只能识别二进制&#xff0c;但是通过字符编码可以展示出各式各样的语言字符。1.2发展过程 1.计算机是美国人发明的&#xff0c;为了能够让加计算机能够…

汉字编码

http://blog.csdn.net/zzidea/article/details/8497532 C语言编程&#xff0c;基本的类型有字符型&#xff0c;整数型&#xff0c;浮点型。这些类型是我们对事物进行描述所必不可少的东西。即基础&#xff0c;又非常核心。所以必须掌握。 一、 字符集 ASCII GB2…

《Qt5:键盘事件》

QKeyEvent类用来描述了一个键盘事件。常用的键盘事件有两种&#xff1a;按键按下和按键释放&#xff0c;一般按键按下事件用的多一点&#xff0c;下面为键盘按下和释放事件的声明&#xff1a; public:void keyPressEvent(QKeyEvent *event);void keyReleaseEvent(QKeyEvent *ev…