Phone List
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
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.
-
输入
- The first line of input gives a single integer, 1 ≤ t ≤ 10, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 100000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits. 输出
- For each test case, output "YES" if the list is consistent, or "NO" otherwise. 样例输入
-
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
样例输出
-
NO YES
算法分析:法一:先排序必须是 n*logn 的复杂度,在比较相邻的两个字符串是否互为前缀 比较时花的时间为 strlen(s); 时间复杂度为:10^5*log 10^5 *10 ,所以在1s内;这个题起初用的是 sort()和STL 超时了 又改了STL还是超时了,继续把sort()改了用 归并写的 发现 用string 会报错的 最后改用 char 终于险过了 -
View Code
1 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<algorithm> 6 #define N 100010 7 8 using namespace std; 9 10 char list[N][15]; 11 char temp[N][15]; 12 13 void merge(int s1,int e1,int s2,int e2) 14 { 15 16 int i,j,k; 17 i=s1;j=s2;k=0; 18 while(i<=e1&&j<=e2) 19 { 20 if(strcmp(list[i],list[j])<0) strcpy(temp[k++],list[i++]); 21 else strcpy(temp[k++],list[j++]); 22 } 23 while(i<=e1) strcpy(temp[k++],list[i++]); 24 while(j<=e2) strcpy(temp[k++],list[j++]); 25 for(k=0,i=s1;i<=e2;i++,k++) strcpy(list[i],temp[k]); 26 } 27 28 void mergesort(int s,int e) 29 { 30 int m=0; 31 if(s<e) 32 { 33 m=(s+e)>>1; 34 mergesort(s,m); 35 mergesort(m+1,e); 36 merge(s,m,m+1,e); 37 } 38 } 39 40 bool judge(char *s1,char *s2) 41 { 42 int i=0,j=0,len1,len2; 43 len1=strlen(s1);len2=strlen(s2); 44 while(i<len1&&j<len2) 45 { 46 if(s1[i]==s2[j]) 47 { 48 i++;j++; 49 } 50 else return false; 51 } 52 if(i==len1||j==len2) return true; 53 } 54 55 int main() 56 { 57 int test; 58 scanf("%d",&test); 59 while(test--) 60 { 61 int n; 62 scanf("%d",&n); 63 int i; 64 for(i=0;i<n;i++) 65 { 66 scanf("%s",list[i]); 67 } 68 mergesort(0,n-1); 69 bool yes=true; 70 for(i=0;i<=n-2;i++) 71 { 72 if(judge(list[i],list[i+1])) 73 { 74 yes=false;break; 75 } 76 } 77 if(yes) printf("YES\n"); 78 else printf("NO\n"); 79 } 80 return 0; 81 } 82