您的位置:首页 > 其它

poj3630 Phone List 字典树

2016-02-19 19:58 267 查看
DescriptionGiven 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 911Alice 97 625 999Bob 91 12 54 26In 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.InputThe 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 phonenumber on each line. A phone number is a sequence of at most ten digits.OutputFor 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
用字典树试试,第一次用字典树,有好几个地方需要注意一下,都在注释里面了...
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;struct trie{int cnt;struct trie* erza[10];}node[100005];//开大一点int num=0;char number[100005][11];//开大一点trie* build(){trie* p=&node[num++];p->cnt=0;for(int k=0;k<10;k++)p->erza[k]=NULL;//不要忘记初始化return p;}void insert(trie *&root,char *number)//一定要加&符号.....{int i=0;if(root==NULL)root=build();trie* p=root;while(number[i]){if(!p->erza[number[i]-'0'])p->erza[number[i]-'0']=build();p=p->erza[number[i]-'0'];p->cnt++;i++;}}bool pd(trie* root,char* number){int i=0;if(root==NULL)return true;trie* p=root;while(number[i]){p=p->erza[number[i]-'0'];if(p->cnt==1)return false;i++;}return true;}int n;int main(){int t,i,j;cin>>t;trie *root;while(t--){bool flag=true;cin>>n;root=NULL;for(i=0;i<n;i++){cin>>number[i];insert(root,number[i]);}for(i=0;i<n;i++){if(pd(root,number[i])){flag=false;break;}}if(flag)cout<<"YES\n";else cout<<"NO\n";num=0;}}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: