Sicily 1426. Phone List 解题报告

题目:

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:
• Emergency 911
• Alice 97 625 999
• 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

 

 思路:

用string 类型数组读进所有电话号码,然后用sort函数对其进行排序。

排序与每个号码的长短无关(前面相同的较短的较小),而是从首位开始逐位比较。

如对13,123,124,11456使用sort函数进行排序,结果会是11456,123,124,13

这样排序之后如果有不相容的两个号码肯定会出现在相邻的两位了,所以对整个数组所有相邻的两位逐位进行比对即可得到结果。

 

 

 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 
 5 int main(){
 6     int testcases;
 7     cin>>testcases;
 8     while(testcases--){
 9         int num_of_phone_number;
10         bool consistent=true;//If two numbers are found inconsistent,it will be false
11         cin>>num_of_phone_number;
12         string numbers[num_of_phone_number];
13         for(int i=0;i<num_of_phone_number;i++){
14             cin>>numbers[i];
15         }
16         sort(numbers,numbers+num_of_phone_number);
17         //Now if inconsistent numbers exist,they must be adjacent
18         for(int i=0;i<num_of_phone_number-1;i++){//linear search every two numbers
19             int len=numbers[i].length();
20             bool match=true;
21             for(int j=0;j<len;j++){
22                 if(numbers[i][j]!=numbers[i+1][j]){
23                     match=false;
24                     break;
25                 }
26             }
27             if(match){
28                 cout<<"NO"<<endl;
29                 consistent=false;
30                 break;
31             }
32         }
33         if(consistent)
34             cout<<"YES"<<endl;
35     }
36     return 0;
37 }

 

 

posted @ 2013-11-04 00:15  Jolin123  阅读(418)  评论(0编辑  收藏  举报