POJ 3630 字典树

http://poj.org/problem?id=3630

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个电话号码,若每一个电话号码都不是其他电话号码的前缀,则输出"YES",否则输出"NO"。

思路:字典树,用sum[i]表示以从字典树根结点0到i结点连成的字符串为前缀的电话号码的个数,最后统计以每个电话号码作为前缀的个数之和,若和等于n则输出"YES",否则输出"NO"。下面的代码用了一个check数组来记录每个电话号码在字典树中存储的位置的最终编号,方便进行最后的统计操作。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#define INF 0x3f3f3f3f
using namespace std;

int tree[300000][10];
int sum[300000];
int check[10005];
char s[15];
int tot;
int num;

inline void Insert()
{
	int root=0;
	int len=strlen(s);
	for(int i=0;i<len;i++)
	{
		int id=s[i]-48;
		if(!tree[root][id])
			tree[root][id]=++tot;
		++sum[tree[root][id]];
		root=tree[root][id];
	}
	check[++num]=root;//记录第i个号码在字典树的最终编号
}

inline void query()
{
	int cnt=0;
	for(int i=1;i<=num;i++)
		if(sum[check[i]]==1)
			++cnt;
	printf("%s\n",cnt==num?"YES":"NO");
}

int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		{
			scanf("%s",s);
			Insert();
		}
		query();
		memset(check,0,sizeof(check));
		memset(tree,0,(tot+1)*sizeof(tree[0]));//注意是tot+1 因为下标从0开始
		memset(sum,0,(tot+1)*sizeof(int));
		tot=num=0;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/88761363