HDU1671 字典树

Posted LuZhiyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU1671 字典树相关的知识,希望对你有一定的参考价值。

Phone List

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


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
 
题意:
一次给出n个电话号码,如果刚给出的一个电话号码的前几位包含前面给出的某一个号码则这个号码不能拨打(输入那前几位时就会马上打出去了)。
代码:
 1 //字典树的权值作为标记点,每输入一个号码,查找他每一位的val值有没有等于1的,如果没有就把他放入字典树他的最后一
 2 //位的val值置为1,如果有说明与前面的某一个冲突。
 3 #include<iostream>
 4 #include<cstdio>
 5 #include<cstring>
 6 using namespace std;
 7 const int MAX=1000000;
 8 const int CON=10;
 9 int nod[MAX][CON],val[MAX];
10 int sz;
11 void init()
12 {
13     sz=1;
14     memset(nod[0],0,sizeof(nod[0]));
15     val[0]=0;
16 }
17 void insert(char s[])
18 {
19     int len=strlen(s);
20     int rt=0;
21     for(int i=0;i<len;i++)
22     {
23         int id=s[i]-0;
24         if(nod[rt][id]==0)
25         {
26             memset(nod[sz],0,sizeof(nod[sz]));
27             nod[rt][id]=sz;
28             val[sz++]=0;
29         }
30         rt=nod[rt][id];
31     }
32     val[rt]=1;
33 }
34 int search(char s[])
35 {
36     int len=strlen(s);
37     int rt=0,cnt=0;
38     for(int i=0;i<len;i++)
39     {
40         int id=s[i]-0;
41         if(nod[rt][id]==0)
42         return 0;
43         rt=nod[rt][id];
44         if(val[rt]==1)
45         return 1;
46     }
47 }
48 int main()
49 {
50     char ch[20];
51     int t,n,flag;
52     scanf("%d",&t);
53     while(t--)
54     {
55         init();
56         scanf("%d",&n);
57         flag=0;
58         for(int i=1;i<=n;i++)
59         {
60             scanf("%s",ch);
61             if(flag) continue;
62             flag=search(ch);
63             insert(ch);
64         }
65         if(flag) printf("NO\n");
66         else printf("YES\n");
67     }
68     return 0;
69 }

 

以上是关于HDU1671 字典树的主要内容,如果未能解决你的问题,请参考以下文章

字典树模板+HDU 1671 ( Phone List )(字典树)

(字典树)HDU - 1671 Phone List

HDU1671 水题字典树

Phone List HDU - 1671 字典树

poj3630||hdoj1671(字典树)

hdu 1671 Phone List