首页 > 代码库 > POJ 3630 Phone List
POJ 3630 Phone List
Phone List
64-bit integer IO format: %lld Java class name: Main
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
2391197625999911254265113123401234401234598346
Sample Output
NOYES
Source
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib>10 #include <string>11 #include <set>12 #include <stack>13 #define LL long long14 #define pii pair<int,int>15 #define INF 0x3f3f3f3f16 using namespace std;17 struct trie {18 int wd[10];19 bool flag;20 void init() {21 memset(wd,-1,sizeof(wd));22 flag = false;23 }24 };25 trie dic[100000];26 int tot,n;27 char str[10010];28 bool insertWd(int root,char *s) {29 for(int i = 0; s[i]; i++) {30 if(dic[root].flag) return false;31 if(dic[root].wd[s[i]-‘0‘] == -1) {32 dic[tot].init();33 dic[root].wd[s[i]-‘0‘] = tot++;34 }35 root = dic[root].wd[s[i]-‘0‘];36 }37 for(int i = 0; i < 10; i++)38 if(dic[root].wd[i] > 0) return false;39 if(dic[root].flag) return false;40 return dic[root].flag = true;41 }42 int main() {43 int t,root = 0;44 scanf("%d",&t);45 while(t--) {46 tot = 1;47 dic[0].init();48 scanf("%d",&n);49 bool flag = true;50 while(n--) {51 scanf("%s",str);52 if(flag) flag = insertWd(root,str);53 }54 flag?puts("YES"):puts("NO");55 }56 return 0;57 }
POJ 3630 Phone List