题目大意:给你一组字符串,让你判断这其中的某一个字符串是不是其他字符串的前缀,如果是输出NO,否则输出YES。
大致思路:这道题我们可以用字典树来做,在每一个字符串后面一个节点加一个标记,标记一下这个字符串已经存在了。在字符串输入的时候判断一下其前缀是否已经出现了。
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
const int MAXN = 1e5 + 10;
int trie[MAXN][10],tot;
bool ed[MAXN];
char ss[MAXN][12];
bool search(char *s){
int len = strlen(s),p = 1;
for(int i = 0; i < len; i++){
int ch = s[i] - '0';
if(trie[p][ch] == 0) trie[p][ch] = ++tot;
p = trie[p][ch];
if(ed[p]) return true;
}
for(int i = 0; i < 10; i++){
if(trie[p][i]) return true;
}
ed[p] = true;
return false;
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d",&t);
while(t--){
memset(ed,0,sizeof(ed));
memset(trie,0,sizeof(trie));
int n;
scanf("%d",&n);
bool flag = false;
tot = 1;
for(int i = 0; i < n; i++){
scanf("%s",ss[i]);
if(search(ss[i])) flag = true;
}
if(flag) puts("NO");
else puts("YES");
}
return 0;
}