码迷,mamicode.com
首页 > 其他好文 > 详细

Phone List

时间:2018-07-11 15:11:49      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:cout   style   false   两种   flag   let   lines   span   log   

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. 

InputThe 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.OutputFor 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 <bits/stdc++.h>
 2 using namespace std;
 3 int tree[100100][15];
 4 int val[100100];
 5 int pos = 1;
 6 
 7 bool insert(string s){
 8     int root = 0;
 9     bool prime = true;
10     for(int i=0;i<s.length();i++){
11         int n = s[i]-0;
12         if(!tree[root][n]){
13             tree[root][n] = pos++;
14         }
15         if(val[root]){
16             prime = false;
17         }
18         root = tree[root][n];
19     }
20     val[root] = 1;
21     for(int i = 0; i < 10; i++){
22         if(tree[root][i])
23             prime = false;
24     }
25     return prime;
26 }
27 
28 int main() {
29     int n,m;
30     ios::sync_with_stdio(false);
31     cin.tie(0);
32     cin>>n;
33     while(n--){
34         cin>>m;
35         string s;
36         bool flag = true;
37         while(m--){
38             cin>>s;
39             if(!insert(s)){
40                 flag = false;
41             }
42         }
43         if(flag){
44             cout<<"YES"<<endl;
45         }else{
46             cout<<"NO"<<endl;
47         }
48         pos = 1;
49         memset(tree,0,sizeof(tree));
50         memset(val,0,sizeof(val));
51     }
52     return 0;
53 }

 



Phone List

标签:cout   style   false   两种   flag   let   lines   span   log   

原文地址:https://www.cnblogs.com/zllwxm123/p/9293790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!