1. 程式人生 > >Phone List

Phone List

min sca his algorithm test you ber scrip using

Time Limit: 1000MS Memory Limit: 65536K

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
Source

Nordic 2007

題意:多組數據,對於每組數據

有n個數字串,問這n個串中是否有一個串是另一個串的前綴

如果有,輸出“NO”否則輸出“YES”

題解:

用Tire樹實現,但是因為多組數據,每一次都要清空

所以在插入的時候在清空,並且動態插入

否則要麽RE,要麽MLE

特殊情況詳見代碼

技術分享圖片
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 #include<cmath>
 5 #define ll long long
 6 #include<cstring>
 7 #include<string>
 8 #define DB double
 9 using namespace std;
10 int T,n,tot,t[100010][10];
11 bool fg,v[100100],mark;
12 char s[100010];
13 void ins(int len)
14 {
15     int now=0;mark=0;
16     for(int i=1;i<=len;++i)
17     {
18         int k=s[i]-0;
19         if(!t[now][k]) t[now][k]=++tot,mark=1;
20         //這是一個新的節點,說明到現在為止,這個串新開辟了位置,肯定不是之前某個串的前綴
21         now=t[now][k];
22         if(v[now]) fg=1;
23         //遇到了之前某個串的結尾。。肯定不符合題意
24     }
25     if(!mark) fg=1;
26     //到插入整個字符了還沒有開辟新位置,顯然新插入的字符串是之前某個串的前綴
27     v[now]=1;
28 }
29 int main()
30 {
31     scanf("%d",&T);
32     while(T--)
33     {
34         tot=0;fg=0;
35         memset(t,0,sizeof(t));
36         memset(v,0,sizeof(v));
37         scanf("%d",&n);
38         for(int i=1;i<=n;++i)
39         {
40             scanf("%s",s+1);
41             if(!fg)ins(strlen(s+1));
42         }
43         if(fg) puts("NO");
44         else puts("YES");
45     }
46     return 0;
47 }
View Code

若言言悅耳,事事悅心,便把此生埋在鴆毒中矣。

Phone List