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;
}
05-树9 Huffman Codes的更多相关文章
- PAT 05-树8 Huffman Codes
以现在的生产力,是做不到一天一篇博客了.这题给我难得不行了,花了两天时间在PAT上还有测试点1没过,先写上吧.记录几个做题中的难点:1.本来比较WPL那块我是想用一个函数实现的,无奈我对传字符串数组无 ...
- 05-树9 Huffman Codes及基本操作
哈夫曼树与哈弗曼编码 哈夫曼树 带权路径长度(WPL):设二叉树有n个叶子结点,每个叶子结点带有权值 Wk,从根结点到每个叶子结点的长度为 Lk,则每个叶子结点的带权路径长度之和就是: WPL = 最 ...
- pta5-9 Huffman Codes (30分)
5-9 Huffman Codes (30分) In 1953, David A. Huffman published his paper "A Method for the Const ...
- 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 ...
- 哈夫曼树(Huffman Tree)与哈夫曼编码
哈夫曼树(Huffman Tree)与哈夫曼编码(Huffman coding)
- 05-树9 Huffman Codes (30 分)
In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Redunda ...
- 05-树9 Huffman Codes (30 分)
In 1953, David A. Huffman published his paper "A Method for the Construction of Minimum-Redunda ...
- Huffman codes
05-树9 Huffman Codes(30 分) In 1953, David A. Huffman published his paper "A Method for the Const ...
随机推荐
- 增量升级(省流量更新)的Android客户端实现
转载与 zhouhuiah的专栏 http://blog.csdn.net/zhouhuiah/article/details/16939937 本文在以上两篇博客的基础上再增加了异常处理,并将生成的 ...
- JMeter简介
#Jmeter简介JMeter是一个100%纯Java桌面应用,它是Apache组织的开放源代码项目,它是功能和性能测试的工具.JMeter可以用于测试静态或者动态资源的性能.JMeter有以下特性: ...
- Node.js log4js日志记录
这次需要给之前弄的文件服务器添加日志记录,一般每天产生的日志会特别多所以安装日期来划分是最好的,这里我用了express框架,为了适应express框架这里在log.js文件中写了use方法. //日 ...
- 从100PV到1亿级PV网站架构演变
如果你对项目管理.系统架构有兴趣,请加微信订阅号"softjg",加入这个PM.架构师的大家庭 一个网站就像一个人,存在一个从小到大的过程.养一个网站和养一个人一样,不同时期需要不 ...
- mysql显示乱码问题
在select * from table:时往往会出现上图所示乱码现象 此时,输入status,会发现: 此时只要SET NAMES utf8即可解决该问题.此时,再次输入status: 总结:S ...
- 学习记录 java随机数的产生机制
java 随机数 一.在j2se里我们可以使用Math.random()方法来产生一个随机数,这个产生的随机数是0-1之间的一个double,我们可以把他乘以一定的数,比如说乘以100,他就是个100 ...
- java学习之(垃圾回收)
程序无法精确控制java垃圾回收的时机,但依然可以强制系统进行垃圾回收--这种强制只是通知系统进行垃圾回收, 但系统是否进行垃圾回收依然不确定.大部分时候,程序强制系统垃圾回收后总会有一些效果,强制系 ...
- Ugly Window 【acm题】
话说好久没有碰acm题目了.............................. 看到Ugly Window这道题目,没有多想,就直接先找到字母的连续长度和连续高度,并统计该字母的总个数,然后用 ...
- PHP isset()与empty()的区别
PHP的isset()函数 一般用来检测变量是否设置 格式:bool isset ( mixed var [, mixed var [, ...]] ) 功能:检测变量是否设置 返回值: 若变量不存在 ...
- Java 对字符反转操作。
//把一段字符串反转后大小写互换位置 public class test_demo { public static void main(String[] args)throws Exception { ...