1471:【例题1】Phone List
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 2918 通过数: 1005
【题目描述】
原题来自:POJ 3630
给定 n 个长度不超过 10 的数字串,问其中是否存在两个数字串 S,T,使得 S 是 T 的前缀,多组数据。
【输入】
第一行一个整数 T,表示数据组数。
对于每组数据,第一行一个数 n,接下来 n 行输入 n 个数字串。
【输出】
对于每组数据,若存在两个数字串 S,T,使得 S 是 T 的前缀,则输出 NO ,否则输出 YES 。
请注意此处结果与输出的对应关系!
【输入样例】
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
【输出样例】
NO
YES
【提示】
数据范围:
对于 100% 的数据,1≤T≤40,1≤n≤104 。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int const N=1e5+5;
int ch[N][11],tot=1;
bool bo[N];
char a[101];
bool word1(char *s){
int l=strlen(s);
bool f=false;
int u=1;
for(int i=0;i<l;i++){
int v=int(s[i])-'0';
if(!ch[u][v]){
ch[u][v]=++tot;
}
else if(i==l-1){
f=true;
}
u=ch[u][v];
if(bo[u]==true)f=true;
}
bo[u]=true;
return f;
}
int main()
{
int t;
cin>>t;
while(t--){
int n;
cin>>n;
memset(ch,0,sizeof(ch));
memset(bo,false,sizeof(bo));
bool o=false;
tot=1;
for(int k=1;k<=n;k++){
scanf("%s",a);
if(word1(a))o=true;
}
if(o==true){
cout<<"NO"<<endl;
}
else cout<<"YES"<<endl;
}
return 0;
}