Phone List hdu1671

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


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
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
 
Sample Output
NO YES
 
题意:给出一些数字,判断这些数字中是否有数字是其他数字的前缀。
分析:字典树
 
 1 #include<cstring>
 2 #include<cstdio>
 3 #include<iostream>
 4 #include<string>
 5 
 6 using namespace std;
 7 #define maxn 1000900
 8 
 9 int dic[maxn][15],val[maxn],flag,cnt;
10 
11 void inst(string s)
12 {
13     int u=0,v,len;
14     len=s.length();
15     for(int i=0;i<len;i++)
16     {
17         v=s[i]-'0';
18         if(!dic[u][v])
19         {
20             dic[u][v]=++cnt;// 构造链表 
21             memset(dic[cnt],0,sizeof(dic[cnt]));//优化
22         }
23         u=dic[u][v]; //u节点与v节点相连 dic的值指向下一个节点
24       if(i==len-1) val[u]++;// 标记该字符串结束位置
25     }
26 }
27 
28 void get(string s)
29 {
30     int u=0,v,len;
31     len=s.length();
32     for(int i=0;i<len-1;i++)
33     {
34         v=s[i]-'0';
35         if(val[dic[u][v]]) //如果该字符串结束之前发现有其他字符串结束点 说明产生前缀
36         {
37             flag=0;
38             return ;
39         }
40         u=dic[u][v];
41     }
42 }
43 
44 int main()
45 {
46     int T;
47     scanf("%d",&T);
48     while(T--)
49     {
50         int n;
51         string s[100000];
52         scanf("%d",&n);
53         memset(dic[0],0,sizeof(dic[0]));
54         memset(val,0,sizeof(val));
55         cnt=0;
56         flag=1;
57         for(int i=0;i<n;i++)
58         {
59             cin>>s[i];
60             if(flag) inst(s[i]); //  这里以及下面最好都优化一下 不然会T
61             if(flag) get(s[i]);
62         }
63         for(int i=0;i<n&&flag;i++)
64             if(flag) get(s[i]);
65         else break;
66         if(flag) printf("YES
");
67         else printf("NO
");
68     }
69 }
原文地址:https://www.cnblogs.com/wsaaaaa/p/4293628.html