0%

HDU1671题:Trie判断前缀

题目

题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1671

Phone List

Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27428 Accepted Submission(s): 9083

Problem 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:

  1. Emergency 911
  2. Alice 97 625 999
  3. 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

1
2
3
4
5
6
7
8
9
10
11
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

1
2
NO
YES

题解

首先利用输入建造一棵Trie,然后再利用每个输入跑Trie,判断是否为两种情况

1.有两个字符串重合,也就是Trie节点计数大于1,这种情况就是NO

2.一个字符串依附于另一个字符串上,那么如果Trie节点计数等于1且下一个字符不是’\0’,这种情况也是NO

剩下的情况就都是YES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=(int)1e6+10;

int tot,root,son[maxn][10];
int flag[maxn];
char s[10010][20];

void Trie(){
memset(son[1],0,sizeof(son[1]));
flag[1]=false;
root=tot=1;
}

void insert(const char* str){
int *cur=&root;
for(const char *p=str;*p;p++){
cur=&son[*cur][*p-'0'];
if(!*cur){
*cur=++tot;
memset(son[tot],0,sizeof(son[tot]));
flag[tot]=0;
}
}
flag[*cur]++;
}

bool query(const char *str){
int *cur=&root;
for(const char *p=str;*p&&*cur;p++) {
cur = &son[*cur][*p - '0'];
if(flag[*cur]>1||(flag[*cur]==1&&*(p+1)!='\0'))
return false;
}
return true;
}

int main(){
int T,n;
scanf("%d",&T);
while(T--){
int f=1;
Trie();
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%s",s[i]),insert(s[i]);
for(int i=0;i<n;i++){
if(!query(s[i])){
f=0;
printf("NO\n");
break;
}
}
if(f)
printf("YES\n");
}
return 0;
}