poj--3630 Phone List(Trie字典树)

3630-Phone List

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 34575 Accepted: 9924

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

Source

Nordic 2007

【题意】给定n个长度不超过10的字符串,判断是否有一个串为另一个串的前缀。

【注意】有输出NO,无输出YES。

【分析】将所有字符串构成一棵Trie,并可以在构建过程中顺便判断答案。若当前串插入后没有新建任何结点,则当前串必然为已插入的某个串的前缀;若插入过程中,有某个经过的结点已经到达串结尾标记,则之前插入的某个串是该串的前缀。

【代码】

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int N=1e5+5;
const int Z=10;
int T,n,tot;
int ch[N][Z];
bool bo[N];
char s[20];
void clear()
{
	memset(ch,0,sizeof(ch));
	memset(bo,false,sizeof(bo));
}
bool insert(char *s)
{
	int len=strlen(s);
	int u=1;
	bool flag=false;
	for(int i=0;i<len;i++)
	{
		int c=s[i]-'0';
		if(!ch[u][c])
			ch[u][c]=++tot;
		else if(i==len-1)
			flag=true;
		u=ch[u][c];
		if(bo[u])
			flag=true;//经过某个有标记的结点 
	}
	bo[u]=true;
	return flag;
}
int main()
{
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		tot=1;	//表示建立一个空节点作为Trie树的根 
		clear();
		bool ans=false;
		for(int i=1;i<=n;i++)
		{
			scanf("%s",s);
			if(insert(s))
				ans=true;
		}	
		if(ans) puts("NO");
		else puts("YES");
	}
	return 0;
}

摘于书《信息学奥赛》

    原文作者:Trie树
    原文地址: https://blog.csdn.net/qq_38735931/article/details/82792531
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞