05-树9 Huffman Codes
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:
//Huffman编码不唯一
//Huffman编码是最优编码,但最优编码不一定是Huffman编码
//需要满足的条件
//1最优:wpl最小 建立Huffman树计算最小wpl判断学生的提交是否正确
//2无歧义:前缀码 建树过程中检查是否满足前缀码要求
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MinData -1
#define N 64
typedef struct HuTreeNode *HuffmanTree;
typedef struct HNode *Heap;
typedef struct BiTreeNode *BinTree;
struct HuTreeNode {
int Weight;
HuffmanTree Left, Right;
};
struct HNode {
HuffmanTree* Data;
int Size;
};
struct BiTreeNode {
int flag;
BinTree Left, Right;
};
HuffmanTree BuiltHuffman(Heap H);
HuffmanTree DeleteMinHeap(Heap H);
void InsertMinHeap(Heap H, HuffmanTree HT);
int Wpl(HuffmanTree HT, int depth);
void CheckPrefixcode(BinTree BT, char *str, int *flag);
BinTree Delete(BinTree BT);
int main(void) {
int i, n, m, wpl, flag, frequency[N], w;
char ch, str[N];
Heap H = (Heap)malloc(sizeof(struct HNode));
HuffmanTree HT;
BinTree BT;
scanf("%d\n", &n);
H->Data = (HuffmanTree*)malloc((n + 1)*sizeof(HuffmanTree));
H->Data[0] = (HuffmanTree)malloc(sizeof(struct HuTreeNode));
H->Data[0]->Weight = MinData;
H->Size = 0;
for (i = 1;i <= n;i++) {
ch = getchar();
if(!isalpha(ch))
ch = getchar();
scanf(" %d", &frequency[i]);
HT = (HuffmanTree)malloc(sizeof(struct HuTreeNode));
HT->Weight = frequency[i];
HT->Left = HT->Right = NULL;
InsertMinHeap(H, HT);
}
HT = BuiltHuffman(H);
w = Wpl(HT, 0);
ch = getchar();
scanf("%d\n", &m);
while (m--) {
wpl = 0;
flag = 0;
BT = (BinTree)malloc(sizeof(struct BiTreeNode));
BT->flag = 0;
BT->Left = BT->Right = NULL;
for (i = 0;i < n;i++) {
scanf("%c %s\n", &ch, str);
wpl += strlen(str) * frequency[i+1];
/*其实可以先检测一下wpl是否相同,不同的话也就不用检测是否前缀码了*/
if(!flag) //这一行其实不需要也行,反正肯定也要执行,PTA已经试过
CheckPrefixcode(BT, str, &flag);
}
if (flag || wpl > w)
printf("No\n");
else printf("Yes\n");
BT = Delete(BT);
}
}
//建立Huffman树
HuffmanTree BuiltHuffman(Heap H) {
int i, k = H->Size - 1;
HuffmanTree HT;
for (i = 0;i < k;i++) {
HT = (HuffmanTree)malloc(sizeof(struct HuTreeNode));
HT->Left = DeleteMinHeap(H);
HT->Right = DeleteMinHeap(H);
HT->Weight = HT->Left->Weight + HT->Right->Weight;
InsertMinHeap(H, HT);
}
return DeleteMinHeap(H);
}
//从最小堆中删除元素
HuffmanTree DeleteMinHeap(Heap H) {
int i, child;
HuffmanTree MinItem, LastItem;
MinItem = H->Data[1];
LastItem = H->Data[H->Size--];
for (i = 1;i * 2 <= H->Size;i = child) {
child = i * 2;
if (child < H->Size && H->Data[child + 1]->Weight < H->Data[child]->Weight)
child++;
if(LastItem->Weight > H->Data[child]->Weight)
H->Data[i] = H->Data[child];
else break;
}
H->Data[i] = LastItem;
return MinItem;
}
//向最小堆中插入元素
void InsertMinHeap(Heap H, HuffmanTree HT) {
int i;
for (i = ++H->Size; H->Data[i / 2]->Weight > HT->Weight; i /= 2)
H->Data[i] = H->Data[i / 2];
H->Data[i] = HT;
}
//计算最优编码长度
/*这里如果出现一种情况,HT只有左子树没有右子树怎么办? NULL->Left会报错吗?
根据题意是不会,NULL-Left结果还是NULL*/
int Wpl(HuffmanTree HT, int depth) {
if (!HT->Left && !HT->Right)
return depth*HT->Weight;
else
return Wpl(HT->Left, depth + 1) + Wpl(HT->Right, depth + 1);
}
//检查是否为前缀码
void CheckPrefixcode(BinTree BT, char *str, int *flag) {
size_t i;
for (i = 0;i < strlen(str);i++) {
if (BT->flag) //非叶子节点存在元素
{
*flag = 1;
return;
}
if (str[i] == '0') {
if (!BT->Left) {
BinTree T = (BinTree)malloc(sizeof(struct BiTreeNode));
T->flag = 0;
T->Left = T->Right = NULL;
BT->Left = T;
}
BT = BT->Left;
}
else {
if (!BT->Right) {
BinTree T = (BinTree)malloc(sizeof(struct BiTreeNode));
T->flag = 0;
T->Left = T->Right = NULL;
BT->Right = T;
}
BT = BT->Right;
}
}
//该节点将写入元素,如果已经存在元素(重合)或者非叶节点(存在子树),则不是前缀码
if (BT->flag || BT->Left || BT->Right) {
*flag = 1;
return;
}
BT->flag = 1;
}
//删除树
BinTree Delete(BinTree BT) {
if (!BT->Left && !BT->Right) {
free(BT);
BT = NULL;
}
else {
if (BT->Left)
BT->Left = Delete(BT->Left);
if (BT->Right)
BT->Right = Delete(BT->Right);
}
return BT;
}
方法2:
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <malloc.h>
#include <iostream>
using namespace std;
typedef struct LNode{
char name;
int weight;
int parent;
}LNode;
void Select_2min(LNode *hf,int i,int &min1,int &min2);
int GetWeight(LNode *hf, char c, int n);
int main()
{
int n; scanf("%d",&n);
LNode *hf = (LNode*)malloc(sizeof(LNode)*(2*n));
for(int i=0; i<n; i++){
getchar();
scanf("%c %d",&hf[i].name,&hf[i].weight);
hf[i].parent=-1;
}
int min1, min2, WPL=0;
for(int i=n; i<2*n-1; i++){
Select_2min(hf, i, min1, min2);
hf[i].weight = hf[min1].weight+hf[min2].weight;
hf[min1].parent = i;
hf[min2].parent = i;
WPL += hf[i].weight;
hf[i].parent = -1;
}
int m; scanf("%d",&m);
while(m--){
string code[1005];
int sum=0;
char c;
for(int i=0; i<n; i++){
getchar();
cin>>c>>code[i];
sum += GetWeight(hf,c,n)*code[i].length();
}
if(sum!=WPL) printf("No\n");
else{
int flag=0;
for(int i=0; i<n; i++){
int len=code[i].length();
for(int j=0;j<n;j++){
if(i==j) continue;
int len_other=code[j].length();
if(len<=len_other&&code[i]==code[j].substr(0,len)){
flag=1;
break;
}
}
if(flag) break;
}
if(flag) printf("No\n");
else printf("Yes\n");
}
}
}
int GetWeight(LNode *hf, char c, int n){
for(int i=0; i<n; i++)
if(hf[i].name == c)
return hf[i].weight;
}
void Select_2min(LNode *hf,int n,int &min1,int &min2){
int flag=0;
for(int i=0;i<n;i++)
if(!flag && hf[i].parent==-1){min1=i;flag=1;}
else if(flag && hf[i].parent==-1){min2=i;break;}
if(hf[min1].weight > hf[min2].weight){
int t=min1; min1=min2; min2=t;
}
for(int i=0; i<n; i++){
if(hf[i].parent!=-1 || i==min1 || i==min2) continue;
else if(hf[i].weight < hf[min1].weight){
min2=min1; min1=i;
}
else if(hf[i].weight < hf[min2].weight)
min2=i;
}
}
方法3:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MINH -1
#define MAXCODESIZE 63
typedef struct TreeNode *HuffmanTree;
struct TreeNode {
int weight;
HuffmanTree Left, Right;
};
typedef struct TreeNode *ElementType;
typedef struct HeapStruct *MinHeap;
struct HeapStruct {
ElementType *Elements;
int Size;
int Capacity;
};
/* 堆的相关操作:开始 */
MinHeap CreateHeap( int MaxSize )
{
MinHeap H = (MinHeap)malloc(sizeof(struct HeapStruct));
H->Elements = malloc((MaxSize + 1) * sizeof(ElementType));
H->Size = 0;
H->Capacity = MaxSize;
H->Elements[0] = (ElementType)malloc(sizeof(struct TreeNode));
H->Elements[0]->weight = MINH;
return H;
}
void DestoryHeap(MinHeap H)
{
int i;
if (!H) return;
if (H->Elements) {
for (i = 0; i < H->Size; ++i)
free(H->Elements[i]);
free(H->Elements);
}
free(H);
}
int IsFull(MinHeap H)
{
return (H->Size == H->Capacity);
}
int IsEmpty(MinHeap H)
{
return (H->Size == 0);
}
void Insert(MinHeap H, ElementType X)
{
int i;
if (IsFull(H)) return;
i = ++H->Size;
for (; H->Elements[i / 2]->weight > X->weight; i /= 2)
H->Elements[i] = H->Elements[i / 2];
H->Elements[i] = X;
}
ElementType DeleteMin(MinHeap H)
{
int Parent, Child;
ElementType MinItem, X;
if (IsEmpty(H)) return 0;
MinItem = H->Elements[1];
X = H->Elements[H->Size--];
for (Parent = 1; Parent * 2 <= H->Size; Parent = Child) {
Child = Parent * 2;
if ((Child != H->Size) && (H->Elements[Child]->weight > H->Elements[Child + 1]->weight))
Child++;
if (X->weight <= H->Elements[Child]->weight) break;
else
H->Elements[Parent] = H->Elements[Child];
}
H->Elements[Parent] = X;
return MinItem;
}
MinHeap BuildMinHeap(int *freq_arr,int n)
{
int i;
ElementType data;
MinHeap H;
H = CreateHeap(n);
for (i = 0; i < H->Capacity; ++i) {
data = (ElementType)malloc(sizeof(struct TreeNode));
data->weight = freq_arr[i];
data->Left = 0; data->Right = 0;
Insert(H, data);
}
return H;
}
/* 堆的相关操作:结束 */
void DestoryCharFreq(int *freq_arr)
{
if (!freq_arr) return;
free(freq_arr);
}
void DestoryHuffmanTree(HuffmanTree HT)
{
if (!HT) return;
DestoryHuffmanTree(HT->Left);
DestoryHuffmanTree(HT->Right);
free(HT);
}
int *readPair(int n)
{
int i; char c;
int *freq_arr;
freq_arr = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf(" %c %d", &c, &freq_arr[i]);
}
return freq_arr;
}
int HuffmanTreeWPL(int *freq_arr, int n)
{
int i, wpl = 0;
MinHeap H;
HuffmanTree T;
H = BuildMinHeap(freq_arr, n); // 根据读入数据建立小顶堆
for (i = 1; i < H->Capacity; ++i) {
T = (HuffmanTree)malloc(sizeof(struct TreeNode));
T->Left = DeleteMin(H);
T->Right = DeleteMin(H);
T->weight = T->Left->weight + T->Right->weight;
Insert(H, T);
wpl += T->weight;
}
T = DeleteMin(H);
DestoryHeap(H);
DestoryHuffmanTree(T); // 销毁Huffman树所占空间
return wpl;
}
void init_codeArr(char *code) // 初始化code数组每个元素为\0
{
int i;
for (i = 0; i < MAXCODESIZE && code[i] != '\0'; ++i)
code[i] = '\0';
}
HuffmanTree createTreeNode()
{
HuffmanTree HT;
HT = (HuffmanTree)malloc(sizeof(struct TreeNode));
HT->weight = 1; HT->Left = 0; HT->Right = 0;
return HT;
}
// 这里使用struct TreeNode结构体,其中的weight用来表示是否为本次code新添加结点,若是则为1,否则为0
HuffmanTree RecoverHFTreeByCode(HuffmanTree HT, char *code, int *flag, int *counter)
{
int i; HuffmanTree node;
if (!HT) {
HT = createTreeNode();
++(*counter);
}
for (i = 0, node = HT; code[i] != '\0'; ++i) {
// 第一种情况:该结点不是新添加结点,并且没有左右孩子,即之前字符对应的子节点
// 说明之前某字符编码是该编码的前缀码
if (node->weight == 0 && !node->Left && !node->Right) {
(*flag) = 0;
break;
}
node->weight = 0;
if (code[i] == '0') { // 读到0向左孩子走一位
if (!node->Left) {
node->Left = createTreeNode();
++(*counter);
}
node = node->Left;
} else {
if (!node->Right) {
node->Right = createTreeNode();
++(*counter);
}
node = node->Right;
}
}
// 第二种情况:读完所有code后,该位置有孩子结点,说明该编码是之前某字符编码的前缀码
if (node->Left || node->Right)
(*flag) = 0;
return HT;
}
void check_code(int *freq_arr, int n, int wpl)
{
int i, sum_wpl, flag, counter; char c;
HuffmanTree HT;
char code[MAXCODESIZE] = "\0";
sum_wpl = 0; flag = 1; counter = 0; HT = 0;
for (i = 0; i < n; ++i) {
init_codeArr(code);
scanf("\n%c %s", &c, code);
if (flag) { // 判断该次提交是否已经不正确了,如果还正确则继续处理
sum_wpl += strlen(code) * freq_arr[i];
HT = RecoverHFTreeByCode(HT, code, &flag, &counter);
}
}
// 这里有三个判断条件
// 1. 提交的总wpl与预设的完全相同
// 2. 没有前缀码情况出现,此处用flag标识
// 3. 没有度为1的结点,此处的counter表示生成的Huffman树结点数,如果正确应该等于2*n-1,n为叶节点个数,即所有字符数
if (sum_wpl == wpl && flag && counter == 2 * n - 1)
printf("Yes\n");
else
printf("No\n");
DestoryHuffmanTree(HT);
}
int main()
{
int n, m, i, wpl;
int *freq_arr;
scanf("%d\n", &n);
freq_arr = readPair(n); // 读入所有字符及其对应频率
wpl = HuffmanTreeWPL(freq_arr, n); // 根据读入字符及频率使用小顶堆建立Huffman树求得WPL值
scanf("%d", &m);
for (i = 0; i < m; ++i) {
check_code(freq_arr, n, wpl);
}
DestoryCharFreq(freq_arr);
return 0;
}