题意:
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"。
每组数据的输出单独一行。
思路:
用字典树来存储。
往字典树中依次插入每个字符串,假设当前字符串为S,则需要判断两种情况,S是否为之前某个字符串的前缀,之前是否有某个字符串是S的前缀。
第一种情况:当字符串S插入结束后,如果最后一个节点是字典树中已经存在的节点,则说明S是之前某个字符串的前缀。
第二种情况:在字符串S插入过程中,如果遇到某一个字典树中的节点是某一个字符串的结尾,则说明存在某个字符串是S的前缀。
总结:
一道用字典树求前缀问题的题目,应理解字典树的结构,在此基础上修改字典树插入的代码,解决题目。
代码:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
bool ans=0;
struct trie
{
static const int N=1010,charset=2;
int tot,root,child[N][charset],flag[N];
Trie()
{
memset(child,-1,sizeof(child));
root=tot=0;
}
void clear()
{
memset(child,-1,sizeof(child));
root=tot=0;
}
void insert(string str)
{
int now=root;
for(int i=0;i<str.size();i++)
{
int x=str[i]-'0';
if(child[now][x]==-1)
{
child[now][x]=++tot;
flag[now]=0;
}
else if(i==str.size()-1||flag[child[now][x]])
ans=1;
now=child[now][x];
}
flag[now]=1;
}
bool query(string str)
{
int now=root;
for(int i=0;i<str.size();i++)
{
int x=str[i]-'0';
if(child[now][x]==-1)
return false;
if(flag[now])
return true;
now=child[now][x];
}
return false;
}
};
int main()
{
string s;
trie t;
int zs=0;
while(cin>>s)
{
zs++;
t.clear();
ans=0;
t.insert(s);
while(cin>>s)
{
if(s=="9")
break;
t.insert(s);
}
if(ans==1)
cout<<"Set "<<zs<<" is not immediately decodable"<<endl;
else
cout<<"Set "<<zs<<" is immediately decodable"<<endl;
}
}