hdu1671字典树

Phone List

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

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

字典树递归算法:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <algorithm>
 4 #include <string.h>
 5 #include <math.h>
 6 #include <vector>
 7 #include <stack>
 8 #include <map>
 9 using namespace std;
10 #define ll long long int
11 #define INF 5100000
12 typedef struct node
13 {
14     struct node *next[10];
15     int n;
16     bool end;
17 } trie;
18 trie *inti()
19 {
20     trie *t;
21     t=(trie *)malloc(sizeof(trie));
22     t->end=0;
23     t->n=0;
24     for(int i=0; i<10; i++) t->next[i]=NULL;
25     return t;
26 }
27 int insert(trie *t,char a[])
28 {
29 
30     if(t->end)return 0;
31     if(*a=='')
32     {
33         if(t->n)return 0;
34         t->end=1;
35         return 1;
36     }
37     t->n++;
38     if(!t->next[*a-'0'])t->next[*a-'0']=inti();
39     return insert(t->next[*a-'0'],a+1);
40 }
41 void del(trie* t)
42 {
43     int i;
44     for(i=0; i<10; ++i)
45     {
46         if(t->next[i] != NULL)
47         {
48             del(t->next[i]);
49         }
50     }
51     free(t);
52 }
53 int main()
54 {
55     int n,m;
56     int i,j;
57     cin>>n;
58     char a[11];
59     for(i=0; i<n; i++)
60     {
61         trie *t;
62         t=inti();
63         cin>>m;
64         int fla=0;
65         for(j=0; j<m; j++)
66         {
67            scanf("%s",a);
68             if(!fla&&!insert(t,a))
69             fla=1;
70         }
71         if(!fla)
72         cout<<"YES"<<endl;
73         else cout<<"NO"<<endl;
74         del(t);
75     }
76 }
View Code
原文地址:https://www.cnblogs.com/ERKE/p/3259108.html