Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 21459 Accepted Submission(s): 7270
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.
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
NOYES
题意:输入的电话号码中是否有号码是其他号码的前缀。
思路:只要判断每个号码是否出现过两次或者两次以上就说明存在有号码是其他号码的前缀。
代码:
#include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; typedef struct node { int num; struct node*child[10]; }node,*Node; Node root; void insert(char *s) { int i,j; int len=strlen(s); Node next=NULL,temp=NULL; if(len==0)return ; next=root; for(i=0;i<len;i++) { if(next->child[s[i]-'0']!=NULL) { next=next->child[s[i]-'0']; (next->num)++; } else { temp=(Node)calloc(1,sizeof(node)); for(j=0;j<10;j++) temp->child[j]=0; next->child[s[i]-'0']=temp; next=temp; next->num=1; } } } int search(char *s) { int i; int len=strlen(s); Node next=NULL; if(len==0)return 0; next=root; for(i=0;i<len;i++) { if(next->child[s[i]-'0']!='\0') { next=next->child[s[i]-'0']; } else return 0; } return next->num; } void release(Node root) { int i; if(NULL==root) return; for(i=0;i<10;i++) { if(root->child[i]!=NULL) { release(root->child[i]); } } free(root); root=NULL; } int main() { int T; cin>>T; char ph[10005][25]; while(T--) { int n; cin>>n; int i,j; bool flag=true; root=(Node)calloc(1,sizeof(node)); for(i=0;i<10;i++) root->child[i]=0; root->num=0; for(i=0;i<n;i++) { scanf("%s",ph[i]); insert(ph[i]); } for(i=0;i<n;i++) { if(search(ph[i])>=2) { flag=false; break; } } if(flag)cout<<"YES"<<endl; else cout<<"NO"<<endl;release(root); } return 0; }