POJ 3630 Phone List(解题报告)

来源:互联网 发布:sql中双引号转义 编辑:程序博客网 时间:2024/05/16 06:01

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

思路:TRIE树的构建以及查找,每棵树的结尾都以VISIT=1来标记,接着只要判断是否经过一个结尾或者是到达结尾还在一棵已经构建完成树内就好。

#include<stdio.h>#include<string.h>char str[10005][11];struct tree{bool visit;tree* child[10];tree(){visit=0;for(int i=0;i<10;i++)child[i]=NULL;}}*root;bool solve(char* st){int i,l=strlen(st);tree* now=root;for(i=0;i<l;i++){if(now->child[st[i]-'0']){now=now->child[st[i]-'0'];if(now->visit==1)return 0;}else{now->child[st[i]-'0']=new tree;now=now->child[st[i]-'0'];}}now->visit=1;for(i=0;i<10;i++)if(now->child[i]!=NULL)return 0;return 1;}void end(tree* now){int i;for(i=0;i<10;i++){if(now->child[i])end(now->child[i]);delete now->child[i];now->child[i]=NULL;}}int main(){int T,n,i;scanf("%d",&T);while(T--){bool value=1;scanf("%d",&n);root=new tree;for(i=0;i<n;i++)scanf("%s",str[i]);for(i=0;i<n;i++){value=solve(str[i]);if(!value)break;}if(value)printf("YES\n");elseprintf("NO\n");end(root);}return 0;}

原创粉丝点击