problem
- 给定n个长度不超过10的数字串(n<10^4)
- 问其中是否存在两个数组串a,b,满足a是b的前缀。存在输出NO,不存在输出YES
solution
- 将所有数字串构建成字典树
- 在插入过程中,如果没有新建任何节点(当前串是之前串的前缀))或者插入过程中经过某个带结尾标记的串(之前串是当前串的前缀),则存在前缀情况。
codes
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5+10;
int tire[maxn][26], val[maxn], tot;
void build(){
tot = 1;
memset(tire,0,sizeof(tire));
memset(val,0,sizeof(val));
}
bool insert(char *s){
bool jingguo = false, xinjian = false;
int len = strlen(s), u = 1;
for(int i = 0; i < len; i++){
int c = s[i]-'0';
if(tire[u][c]==0){
tire[u][c] = ++tot;
xinjian = true;
}
u = tire[u][c];
if(val[u])jingguo = true;
}
val[u] = 1;
if(!xinjian || jingguo)return true;
return false;
}
char s[20];
int main(){
int T;
scanf("%d",&T);
while(T--){
int n;
scanf("%d",&n);
build();
bool ans = false;
for(int i = 1; i <= n; i++){
scanf("%s",s);
if(insert(s))ans = true;
}
if(ans)cout<<"NO
";
else cout<<"YES
";
}
return 0;
}