B - ZJM 与生日礼物(选做)
题目
ZJM 收到了 Q老师 送来的生日礼物,但是被 Q老师 加密了。只有 ZJM 能够回答对 Q老师 的问题,Q老师 才会把密码告诉 ZJM。
Q老师 给了 ZJM 一些仅有 01 组成的二进制编码串, 他问 ZJM:是否存在一个串是另一个串的前缀.
多组数据。每组数据中包含多个仅有01组成的字符串,以一个9作为该组数据结束的标志。
对于第 k 组数据(从1开始标号),如果不存在一个字符串使另一个的前缀,输出"Set k is immediately decodable",否则输出"Set k is not immediately decodable"。
每组数据的输出单独一行
01
10
0010
0000
9
01
10
010
0000
9
Set 1 is immediately decodable
Set 2 is not immediately decodable
思路
注意:
注意字典树结构体的组成、各项函数的编写(参考下面代码)。
代码
#include<iostream>
#include<memory.h>
#include<string.h>
#include<string>
using namespace std;
struct trie
{
static const int maxn=1e3,typen=5;
int root,child[maxn][typen],flag[maxn],tot;
trie()
{
memset(child,-1,sizeof child);
//memset(flag,0,sizeof flag);
root=tot=0;
}
void clear()
{
memset(child,-1,sizeof child);
root=tot=0;
//memset(flag,0,sizeof flag);
}
int insert(char* s)
{
int now=root,res=0;
for(int i=0;i<strlen(s);i++)
{
int x=s[i]-'0';
if(child[now][x]==-1)
{
child[now][x]=++tot;
flag[tot]=0;
}
else if(i==strlen(s)-1||flag[child[now][x]]==1)
{
res=1;
}
now=child[now][x];
}
flag[tot]=1;
return res;
}
};
int main()
{
trie t;
char s[1000];
int ans=0,k=1;
while(cin>>s)
{
if(s[0]=='9')
{
if(ans==1)cout<<"Set "<<k<<" is not immediately decodable"<<endl;
else cout<<"Set "<<k<<" is immediately decodable"<<endl;
ans=0;
t.clear();
k++;
continue;
}
if(t.insert(s)==1)
ans=1;
}
return 0;
}