05-树9 Huffman Codes

时间:2023-03-10 06:51:05
05-树9 Huffman Codes

哈夫曼树

Yes 需满足两个条件:1.HuffmanTree 结构不同,但WPL一定。子串WPL需一致

          2.判断是否为前缀码

  开始判断用的strstr函数,但其传值应为char *,不能用在string类型。所以后来改用substr。

substr(start,length);start为子串起始位置,length为从起始位置的长度。

 #include <iostream>
#include <string>
using namespace std; int main()
{
string str = "",endStr;
endStr = str.substr(,);
cout<< endStr <<endl;
return ;
}
//output:123

View Eg Code

  因为这里用了容器优先队列,且判断前缀码用了暴力求解,substr(start,length);函数。所以 要点:最大N&M,code长度等于63  超时了。

  自己写,会快。

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 NNdistinct 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', '_'}, andf[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 MM student submissions. Each student submission consists of NN 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
 #include <iostream>
#include <cstdio>
#include <string>
#include <queue>
#include <algorithm>
using namespace std; struct HuffTreeNode
{
char c;
int f;
};
struct HuffTreeNode HuffNode[]; struct strNod
{
char c;
string code;
};
struct strNod strNode[]; bool compare(strNod a, strNod b)
{
return a.code.size() < b.code.size();/*长度从小到大排序 */
} /*strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。
如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。*/
/*[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'char* strstr(const char*, const char*)'*/
/*是子串返回true ,否则false */
bool isStrstr(int N)
{
sort(strNode, strNode+N, compare);
for(int i = ; i < N; i ++) {
for(int j = i + ; j < N; j++) {
if( strNode[j].code.substr( , strNode[i].code.size() ) == strNode[i].code )
return true;
}
}
return false;
} int main()
{
int N;
scanf("%d",&N);
priority_queue<int, vector<int>, greater<int> > pq;
for(int i = ; i < N; i++) {
getchar(); /*排除回车 空格的影响 */
scanf("%c",&HuffNode[i].c);
scanf("%d",&HuffNode[i].f);
pq.push(HuffNode[i].f);
}
/*计算HuffmanTree WPL*/
int WPL = ;
int smallA,smallB;
while( !pq.empty() ) {
smallA = pq.top(); pq.pop(); /*取出两个最小的 */
if( !pq.empty() ) {
smallB = pq.top(); pq.pop();
smallA += smallB;
pq.push(smallA); /*求和后push进优先队列 */
}
WPL += smallA;
}
WPL -= smallA; /*求出WPL */
/* printf("WPL = %d",WPL);*/
int M;
scanf("%d",&M);
for(int i = ; i < M; i++) {
int checkWpl = ;
for(int j = ; j < N; j++) {
cin >> strNode[j].c >> strNode[j].code;
checkWpl += strNode[j].code.size() * HuffNode[j].f; //计算wpl
}
/* printf("checkWpl = %d",checkWpl);*/
if(checkWpl == WPL) { /*WPL符合,判断是否是前缀 */
if( isStrstr(N) ) /*有子串,不符合 */
printf("No\n");
else
printf("Yes\n");
}
else
printf("No\n");
}
return ;
}

事实证明,自己写最小堆,并不能达到要求。大头应该是字符串比较那里。

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std; #define MINDATA 0 /* 该值应根据具体情况定义为小于堆中所有可能元素的值 */
#define ERROR -1 struct HNode {
int *Data; /* 存储元素的数组 */
int Size; /* 堆中当前元素个数 */
int Capacity; /* 堆的最大容量 */
};
typedef struct HNode *MinHeap; /* 堆的类型定义 */ struct TreeNode {
char c;
int f;
};
struct TreeNode HuffNode[]; struct strNod
{
char c;
string code;
};
struct strNod strNode[];
MinHeap CreateHeap( int MaxSize );
bool IsFull( MinHeap H );
bool Insert( MinHeap H, int X );
bool IsEmpty( MinHeap H );
int DeleteMin( MinHeap H ); bool compare(strNod a, strNod b)
{
return a.code.size() < b.code.size();/*长度从小到大排序 */
} /*strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。
如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。*/
/*[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'char* strstr(const char*, const char*)'*/
/*是子串返回true ,否则false */
bool isStrstr(int N)
{
sort(strNode, strNode+N, compare);
for(int i = ; i < N; i ++) {
for(int j = i + ; j < N; j++) {
if( strNode[j].code.substr( , strNode[i].code.size() ) == strNode[i].code )
return true;
}
}
return false;
} int main()
{
int N;
scanf("%d",&N);
MinHeap Heap = CreateHeap(N);
for(int i = ; i < N; i++) {
getchar(); /*排除回车 空格的影响 */
scanf("%c",&HuffNode[i].c);
scanf("%d",&HuffNode[i].f);
Insert(Heap, HuffNode[i].f);
} //计算WPL的值
int WPL = ;
int smallA, smallB;
while( !IsEmpty(Heap) ) {
smallA = DeleteMin(Heap);
if( !IsEmpty(Heap) ) {
smallB = DeleteMin(Heap);
smallA += smallB;
Insert( Heap, smallA);
}
WPL += smallA;
}
WPL -= smallA;
// printf("WPL = %d\n",WPL); int M;
scanf("%d",&M);
for(int i = ; i < M; i++) {
int checkWpl = ;
for(int j = ; j < N; j++) {
cin >> strNode[j].c >> strNode[j].code;
checkWpl += strNode[j].code.size() * HuffNode[j].f; //计算wpl
}
/* printf("checkWpl = %d",checkWpl);*/
if(checkWpl == WPL) { /*WPL符合,判断是否是前缀 */
if( isStrstr(N) ) /*有子串,不符合 */
printf("No\n");
else
printf("Yes\n");
}
else
printf("No\n");
}
return ;
} /* 创建容量为MaxSize的空的最小堆 */
MinHeap CreateHeap( int MaxSize )
{ MinHeap H = (MinHeap)malloc(sizeof(struct HNode));
H->Data = (int*)malloc((MaxSize+)*sizeof(int));
H->Size = ;
H->Capacity = MaxSize;
H->Data[] = MINDATA; /* 定义"哨兵"为小于堆中所有可能元素的值*/
return H;
} bool IsFull( MinHeap H )
{
return (H->Size == H->Capacity);
} /* 将元素X插入最小堆H,其中H->Data[0]已经定义为哨兵 */
bool Insert( MinHeap H, int X )
{
if ( IsFull(H) ) {
printf("最小堆已满");
return false;
}
int i = ++H->Size; /* i指向插入后堆中的最后一个元素的位置 */
for ( ; H->Data[i/] > X; i /= )
H->Data[i] = H->Data[i/]; /* 上滤X */
H->Data[i] = X; /* 将X插入 */
return true;
} bool IsEmpty( MinHeap H )
{
return (H->Size == );
} /* 从最小堆H中取出键值为最小的元素,并删除一个结点 */
int DeleteMin( MinHeap H )
{
int Parent, Child;
int MinItem, X; if ( IsEmpty(H) ) {
printf("最小堆已为空");
return ERROR;
} MinItem = H->Data[]; /* 取出根结点存放的最小值 */
/* 用最小堆中最后一个元素从根结点开始向上过滤下层结点 */
X = H->Data[H->Size--]; /* 注意当前堆的规模要减小 */
for( Parent = ; Parent * <= H->Size; Parent = Child ) {
Child = Parent * ;
if( (Child != H->Size) && (H->Data[Child] > H->Data[Child+]) )
Child++; /* Child指向左右子结点的较小者 */
if( X <= H->Data[Child] ) break; /* 找到了合适位置 */
else /* 下滤X */
H->Data[Parent] = H->Data[Child];
}
H->Data[Parent] = X; return MinItem;
}

剪枝、。。。失败

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std; #define MINDATA 0 /* 该值应根据具体情况定义为小于堆中所有可能元素的值 */
#define ERROR -1 struct HNode {
int *Data; /* 存储元素的数组 */
int Size; /* 堆中当前元素个数 */
int Capacity; /* 堆的最大容量 */
};
typedef struct HNode *MinHeap; /* 堆的类型定义 */ struct TreeNode {
char c;
int f;
};
struct TreeNode HuffNode[]; struct strNod
{
char c;
string code;
};
struct strNod strNode[];
MinHeap CreateHeap( int MaxSize );
bool IsFull( MinHeap H );
bool Insert( MinHeap H, int X );
bool IsEmpty( MinHeap H );
int DeleteMin( MinHeap H ); bool compare(strNod a, strNod b)
{
return a.code.size() < b.code.size();/*长度从小到大排序 */
} /*strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。
如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。*/
/*[Error] cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'char* strstr(const char*, const char*)'*/
/*是子串返回true ,否则false */
bool isStrstr(int N)
{
sort(strNode, strNode+N, compare);
for(int i = ; i < N; i ++) {
for(int j = i + ; j < N; j++) {
if( strNode[j].code.substr( , strNode[i].code.size() ) == strNode[i].code )
return true;
}
}
return false;
} int main()
{
int N;
scanf("%d",&N);
MinHeap Heap = CreateHeap(N);
for(int i = ; i < N; i++) {
getchar(); /*排除回车 空格的影响 */
scanf("%c",&HuffNode[i].c);
scanf("%d",&HuffNode[i].f);
Insert(Heap, HuffNode[i].f);
} //计算WPL的值
int WPL = ;
int smallA, smallB;
while( !IsEmpty(Heap) ) {
smallA = DeleteMin(Heap);
if( !IsEmpty(Heap) ) {
smallB = DeleteMin(Heap);
smallA += smallB;
Insert( Heap, smallA);
}
WPL += smallA;
}
WPL -= smallA;
// printf("WPL = %d\n",WPL); int M; scanf("%d",&M);
for(int i = ; i < M; i++) {
int checkWpl = ;
bool overFlag = false; //其中一个字符串超出长度
for(int j = ; j < N; j++) {
cin >> strNode[j].c >> strNode[j].code;
if(strNode[j].code.size() > N-) { //如果有size超出N-1 一定不满足WPL 这里卡一刀希望快些
overFlag = true;
break;
}
checkWpl += strNode[j].code.size() * HuffNode[j].f; //计算wpl
}
/* printf("checkWpl = %d",checkWpl);*/
if(checkWpl == WPL && !overFlag) { /*WPL符合,判断是否是前缀 */
if( isStrstr(N) ) /*有子串,不符合 */
printf("No\n");
else
printf("Yes\n");
}
else
printf("No\n");
}
return ;
} /* 创建容量为MaxSize的空的最小堆 */
MinHeap CreateHeap( int MaxSize )
{ MinHeap H = (MinHeap)malloc(sizeof(struct HNode));
H->Data = (int*)malloc((MaxSize+)*sizeof(int));
H->Size = ;
H->Capacity = MaxSize;
H->Data[] = MINDATA; /* 定义"哨兵"为小于堆中所有可能元素的值*/
return H;
} bool IsFull( MinHeap H )
{
return (H->Size == H->Capacity);
} /* 将元素X插入最小堆H,其中H->Data[0]已经定义为哨兵 */
bool Insert( MinHeap H, int X )
{
if ( IsFull(H) ) {
printf("最小堆已满");
return false;
}
int i = ++H->Size; /* i指向插入后堆中的最后一个元素的位置 */
for ( ; H->Data[i/] > X; i /= )
H->Data[i] = H->Data[i/]; /* 上滤X */
H->Data[i] = X; /* 将X插入 */
return true;
} bool IsEmpty( MinHeap H )
{
return (H->Size == );
} /* 从最小堆H中取出键值为最小的元素,并删除一个结点 */
int DeleteMin( MinHeap H )
{
int Parent, Child;
int MinItem, X; if ( IsEmpty(H) ) {
printf("最小堆已为空");
return ERROR;
} MinItem = H->Data[]; /* 取出根结点存放的最小值 */
/* 用最小堆中最后一个元素从根结点开始向上过滤下层结点 */
X = H->Data[H->Size--]; /* 注意当前堆的规模要减小 */
for( Parent = ; Parent * <= H->Size; Parent = Child ) {
Child = Parent * ;
if( (Child != H->Size) && (H->Data[Child] > H->Data[Child+]) )
Child++; /* Child指向左右子结点的较小者 */
if( X <= H->Data[Child] ) break; /* 找到了合适位置 */
else /* 下滤X */
H->Data[Parent] = H->Data[Child];
}
H->Data[Parent] = X; return MinItem;
}