ZJM 与生日礼物
仅有 01 组成的二进制编码串,是否存在一个串是另一个串的前缀.
输入
多组数据。每组数据中包含多个仅有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 插入过程中,如果遇到某一个字典树中的节点为某一个字符串的结尾,则说明存在某个字符串是 S 的前缀。
字典树模板代码
#include<iostream>
#include<cstring>
using namespace std;
struct Trie{
static const int N=1010,charset=30;
//N表示字典树最多节点个数,charset表示字符种类数
//tot表示节点编号,root表示根节点编号
//child[now][x]表示节点now的第x个儿子
//flag[now]=1表示节点now是一个字符串的结尾
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;
}
//在字典树中插入字符串str
void insert(char *str){
int now=root;
for(int i=0;str[i];i++){
int x=str[i]-'a';
if(child[now][x]==-1){
child[now][x]=++tot;
flag[now]=0;
}
now=child[now][x];
}
flag[now]=1;//标记某节点为一字符串结尾
}
//查询字典树中是否存在某个完整字符串是str的前缀
bool query(char *str){
int now=root;
for(int i=0;str[i];i++){
int x=str[i]-'a';
if(child[now][x]==-1) return false;
if(flag[now]) return true;
now=child[now][x];
}
return false;
}
};
解题代码
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
string s;
int count=1;
struct Trie{
static const int N=1010,charset=30;
//N表示字典树最多节点个数,charset表示字符种类数
//tot表示节点编号,root表示根节点编号
//child[now][x]表示节点now的第x个儿子
//flag[now]=1表示节点now是一个字符串的结尾
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;
}
//在字典树中插入字符串str
int insert(string& str){
int now=root,jud=0,len=str.length();
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]]) jud=1;
//i==len-1且child[now][x]!=-1说明S是之前某个字符串的前缀
//flag[child[now][x]]==1说明之前某个字符串是S的前缀
now=child[now][x];
}
flag[now]=1;//标记某节点为一字符串结尾
return jud;
}
};
Trie t;
int main(){
while(cin>>s){
int ans=0;
t.clear();
while(true){
if(s=="9") break;
if(t.insert(s)==1){
ans=1;
}
cin>>s;
}
if(ans==0){
cout<<"Set "<<count<<" is immediately decodable"<<endl;
}
else{
cout<<"Set "<<count<<" is not immediately decodable"<<endl;
}
count++;
}
}