poj Phone List 3630 (字典树 判断前缀)

来源:互联网 发布:南木梁知txt 编辑:程序博客网 时间:2024/06/13 19:20
Phone List
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 25650 Accepted: 7770

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:

  • 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 withn, the number of phone numbers, on a separate line, 1 ≤ n ≤ 10000. Then followsn 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
//题意:
给n个字符串,判断这些字符串是否存在一个字符串是另一个字符串的前缀。若存在输出NO,否则输出YES。
#include<stdio.h>#include<string.h>#include<algorithm>#define N 100100using namespace std;char s[10100][10];int ch[N][10];int word[N];int sz;int init(){sz=1;memset(ch[0],0,sizeof(ch[0]));memset(word,0,sizeof(word));}void insert(char s[]){int i,j,l=strlen(s);int k=0;for(i=0;i<l;i++){j=s[i]-'0';if(!ch[k][j]){memset(ch[sz],0,sizeof(ch[sz]));ch[k][j]=sz++;}k=ch[k][j];word[k]++;}}int find(char s[]){int i,j,l=strlen(s);int k=0;for(i=0;i<l;i++){j=s[i]-'0';k=ch[k][j];if(word[k]==1)return 1;}return 0;}int main(){init();int t,n,i;int flag;scanf("%d",&t);while(t--){scanf("%d",&n);init();for(i=0;i<n;i++){scanf("%s",s[i]);insert(s[i]);}flag=1;for(i=0;i<n;i++){if(!find(s[i])){flag=0;break;}}if(flag)printf("YES\n");elseprintf("NO\n");}return 0;}

0 0