字典树问题
插入每个字符串前,先判断前面某个字符串是不是该字符串的前缀,或者该字符串是不是前面某个字符串的前缀
详细请看代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100000+100;
int trie[maxn][10],tot;
bool vis[maxn];
inline void insert(char* ch){
int len=strlen(ch);
int root=0;
for(int i=0;i<len;i++){
int ind=ch[i]-'0';
if(!trie[root][ind]) trie[root][ind]=++tot;
root=trie[root][ind];
}
vis[root]=true; //字符串结尾标记
}
inline bool search(char* ch){
int len=strlen(ch);
int root=0;
for(int i=0;i<len;i++){
int ind=ch[i]-'0';
if(!trie[root][ind]) return false;
root=trie[root][ind];
if(vis[root]) return true;//前面某个字符串是该字符串的前缀
}
for(int i=0;i<=9;i++) if(trie[root][i]) return true; //该字符串是前面某个字符串的前缀
return false;
}
int main(){
int T,n;
bool istrue;
scanf("%d",&T);
char ch[20];
while(T--){
tot=0;
memset(trie,0,sizeof(trie));
memset(vis,false,sizeof(vis));
istrue=true;
scanf("%d",&n);
getchar();
for(int i=1;i<=n;i++){
scanf("%s",ch);
if(!istrue) continue;
if(search(ch)) istrue=false;
insert(ch);
}
if(istrue) printf("YES\n");
else printf("NO\n");
}
}