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
一个字符串和字符串集合做匹配,因此考虑用字典树。
往字典树中依次插入每个字符串,假设当前字符串为S
有两种情况需要判断:
S是否是某个字符串的前缀
当字符串插入结束后,其最后一个节点是字典树已经存在的节点,则说明S为之前某个串的前缀。
之前是否有某个字符串是S的前缀
在字符串S的插入过程中,如果遇到某个节点是某个字符串的结尾,说明存在某个字符串是S的前缀。
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
struct iTree{
static const int N=10100,charset=3;
int tot,root,child[N][charset],flag[N];
iTree()
{
memset(child,-1,sizeof(child));
root=tot=0;
}
void clear()
{
memset(child,-1,sizeof(child));
root=tot=0;
}
bool insert(string str)
{
int now=root,f=0,len=str.size();
for(int i=0;i<len;i++)
{
int x=str[i]-'0';
if(child[now][x]==-1)
{
child[now][x]=++tot;
flag[now]=0;
}
else if(i==len-1||flag[child[now][x]])
{
f=1;
}
now=child[now][x];
}
flag[now]=1;
return f;
}
};
string str;
int k=1;
int main()
{
iTree t;
int flag=0;
while(cin>>str)
{
if(str=="9")
{
if(flag==0)
{
cout<<"Set "<<k<<" is immediately decodable\n";
}
else
{
cout<<"Set "<<k<<" is not immediately decodable\n";
}
k++;
t.clear();
flag=0;
}
else
{
int tmp=t.insert(str);
if(tmp==1)
{
flag=1;
}
}
}
}