NYOJ 163 Phone List

 1 //字典树的应用
 2 #include<iostream>
 3 #include<string>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<malloc.h>
 7 using namespace std;
 8 
 9 typedef struct phone{
10     struct phone *num[10];
11     int count;
12 }*Ph;
13 
14 Ph root;
15 int flag;
16 
17 Ph newphone()
18 {
19     Ph p;
20     p = new phone;
21     for(int i=0; i<10; ++i)
22         p->num[i] = NULL;
23     p->count = 0;
24     return p;
25 }
26 
27 bool insert(char s[11])
28 {
29     Ph p = root;
30     int i,k=0;
31     for(i=0; i<strlen(s); ++i)
32     {
33         if(!p->num[s[i] - '0'])
34         {
35             if(p->count > 0)    //说明已经出现过这样的手机号前缀
36                 return false;   //长的接着短的
37             p->num[s[i] - '0'] = newphone();  
38             ++k;               
39         }
40         p = p->num[s[i] - '0'];
41     }
42     ++p->count;  //出现过的手机号标记为1
43     if(!k) return false;  //k为0,说明没有开辟新的结点,也就是说这个手机号包含在已有的手机号里边,即出现过这样的前缀
44     return true;
45 }
46 
47 int main()
48 {
49 //    freopen("in.txt","r",stdin);
50     int t,n,i; 
51     char s[11];
52     cin>>t;
53     while(t--)
54     {
55         root = newphone(); flag = 0;
56         cin>>n;
57         for(i=0; i<n; ++i)
58         {
59             scanf("%s",s);
60             if(flag)continue;
61             if(!insert(s))
62                 flag = 1;
63         }
64         if(flag)cout<<"NO\n";
65         else
66             cout<<"YES\n";
67     }
68     return 0;
69 }
原文地址:https://www.cnblogs.com/yaling/p/3024947.html