Phone List(字典树)

时间:2023-03-08 18:16:16
Phone List
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 25709   Accepted: 7785

Description

Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let's say the phone catalogue listed these numbers:

  • Emergency 911
  • Alice 97 625 999
  • Bob 91 12 54 26

In this case, it's not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob's phone number. So this list would not be consistent.

Input

The first line of input gives a single integer, 1 ≤ t ≤ 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.

Output

For each test case, output "YES" if the list is consistent, or "NO" otherwise.

Sample Input

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

NO
YES
题解:只要找到一个word【k】==1,证明这个单词是新的;
就结束,没找到,证明这个单词是其他单词的前缀;
代码:
 #include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
const int INF=0x3f3f3f3f;
const double PI=acos(-1.0);
const int MAXN=;
int ch[MAXN][],word[MAXN];
char dt[MAXN][];
int sz;
void initial(){
sz=;
mem(word,);
mem(ch[],);
}
void join(char *s){
int len=strlen(s),k=,j;
for(int i=;i<len;i++){
j=s[i]-'';
if(!ch[k][j]){
mem(ch[sz],);
ch[k][j]=sz++;
}
k=ch[k][j];
word[k]++;
}
}
bool find(char *s){
int len=strlen(s),k=,j;
for(int i=;i<len;i++){
j=s[i]-'';
k=ch[k][j];
if(word[k]==)return true;
}
return false;
}
void display(int n){
for(int i=;i<n;i++){
if(!find(dt[i])){
// puts(dt[i]);
puts("NO");
return;
}
}
puts("YES");
}
int main(){
int T,N;
scanf("%d",&T);
while(T--){
initial();
scanf("%d",&N);
for(int i=;i<N;i++){
scanf("%s",dt[i]);
join(dt[i]);
}
display(N);
}
return ;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define P_ printf(" ")
const int INF=0x3f3f3f3f;
const int MAXN=1000010;//要开的足够大
int ch[MAXN][10];
int word[MAXN];
char str[MAXN][15];
int sz;
int N;
void insert(char *s){
int k=0,j;
for(int i=0;s[i];i++){
j=s[i]-'0';
if(!ch[k][j]){
mem(ch[sz],0);
ch[k][j]=sz++;
}
k=ch[k][j];
word[k]++;
}
}
bool find(char *s){
int k=0,j;
for(int i=0;s[i];i++){
j=s[i]-'0';
k=ch[k][j];
if(word[k]==1)return true;
}
return false;
}
bool work(){
for(int i=0;i<N;i++){
// puts("**");
if(!find(str[i]))return false;
}
return true;
}
int main(){
int T;
SI(T);
while(T--){
SI(N);
sz=1;//
mem(ch[0],0);mem(word,0);//
for(int i=0;i<N;i++)scanf("%s",str[i]),insert(str[i]);
if(work())puts("YES");
else puts("NO");
}
return 0;
}