Phone List
Posted ww123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Phone List相关的知识,希望对你有一定的参考价值。
描述
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 ≤ 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.
输出
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
解题思路:考虑一个字符串是不是其它字符串的前缀, 或者其它的字符串是它的前缀, 开始没有考虑到是不是其它子串的情况。
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; struct node { node *next[10]; bool is; node() { is=false; memset(next,NULL,sizeof(next)); } }; int insert(node *root,char s[]) { int i=0; int flag=1; node *p=root; while(s[i]) { int j=s[i++]-‘0‘; if(p->next[j]==NULL) { p->next[j]=new node(); flag=0; } p=p->next[j]; if(p->is==true) return 0; } p->is=true; if(flag==1) return 0; return 1; } int main() { int t,n,m,i,j,k; cin>>n; while(n--) { node *root=new node(); cin>>m; int flag=1; for(i=0;i<m;i++) { char s[11]; scanf("%s",s); if(flag) { int g=insert(root,s); if(g==0) flag=0; } } if(flag) cout<<"YES\n"; else cout<<"NO\n"; } }
以上是关于Phone List的主要内容,如果未能解决你的问题,请参考以下文章