题目:
Phone List |
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) |
Total Submission(s): 235 Accepted Submission(s): 92 |
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 |
Source 2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3) |
Recommend lcy |
题目分析:
这道题,属于Trie的入门级别的题目。但是在这里先介绍1下不用Trie怎样解决这道题。在1堆号码中,
要判断1个号码是不是是其他号码的前缀。我们可以先对这对号码按字典序进行1下排序。然后顺次判断相邻两个号码中是不是有号码是其它号码的前缀便可。整体的时间复杂度要比暴力做法的O(n^2)要好很多。
这里还需要介绍1下的是strncmp这个函数。
strncmp(): 这个函数用来比较s1和s2字符串,这个函数将返回1个值, 它的符号与第1对不同的字符的比较结果相干。如果两个字符串相等的话,strncmp将返回0。如果s1是s2的1个子串的话,s1小于s2。另外还有,函数 int strncmp (const char *s1, const char *s2, size_t size) 此函数与strcmp极其类似。不同的地方是,strncmp函数是指定比较size个字符。也就是说,如果字符串s1与s2的前size个字符相同,函数返回值为0。
代码以下: