码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3630 Phone List

时间:2017-01-13 10:25:48      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:ber   put   emerge   scan   ice   work   pre   rip   ons   

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

 

 

本文作者:ljh2000 
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 

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 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

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

NO
YES


正解:Trie
解题报告:
  1A就是爽。
  询问有没有一个串是另一个串的前缀。
  建一棵Trie树,然后每次check一下,当前单词的最后一个结点是不是之前已经存在,存在则说明是另一个串的前缀;
  如果中间经过了某个结点是之前的某个串的结束结点,也说明存在前缀。
  打个标记即可。

//It is made by ljh2000
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 100011;
int n,tr[MAXN][10],cnt;
bool ok,vis[MAXN];
char ch[12];
inline int getint(){
    int w=0,q=0; char c=getchar(); while((c<‘0‘||c>‘9‘) && c!=‘-‘) c=getchar();
    if(c==‘-‘) q=1,c=getchar(); while (c>=‘0‘&&c<=‘9‘) w=w*10+c-‘0‘,c=getchar(); return q?-w:w;
}

inline void read(){
	if(!ok) { scanf("%s",ch); return ; }
	char c=getchar(); int u=0,now; bool flag;
	while(c>‘9‘ || c<‘0‘) c=getchar();
	while(1) {
		now=c-‘0‘; if(vis[u]) ok=false;
		if(!tr[u][now]) tr[u][now]=++cnt,flag=false; 
		else flag=true;
		u=tr[u][now];
		c=getchar(); if(c<‘0‘||c>‘9‘) break;
	}
	if(vis[u] || flag) { ok=false; return ; }
	vis[u]=1;
}

inline void work(){
	int T=getint();
	while(T--) {
		memset(tr,0,sizeof(tr)); memset(vis,0,sizeof(vis));
		cnt=0; ok=true;
		n=getint(); for(int i=1;i<=n;i++) read();
		if(ok) puts("YES"); else puts("NO");
	}
}

int main()
{
    work();
    return 0;
}

  

POJ3630 Phone List

标签:ber   put   emerge   scan   ice   work   pre   rip   ons   

原文地址:http://www.cnblogs.com/ljh2000-jump/p/6276915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!