poj3630 Phone List 字典树

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
 
 
用字典树试试,第一次用字典树,有好几个地方需要注意一下,都在注释里面了...
 
 
 
 
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct trie{
	int cnt;
	struct trie* erza[10];
}node[100005];//开大一点 
int num=0;
char number[100005][11];//开大一点 
trie* build()
{
	trie* p=&node[num++];
	p->cnt=0;
	for(int k=0;k<10;k++)p->erza[k]=NULL;//不要忘记初始化 
	return p;
}
void insert(trie *&root,char *number)//一定要加&符号..... 
{
	int i=0;
	if(root==NULL)root=build();
	trie* p=root;
	while(number[i])
	{
		if(!p->erza[number[i]-'0'])p->erza[number[i]-'0']=build();
		p=p->erza[number[i]-'0'];
		p->cnt++;
		i++;
	}
}
bool pd(trie* root,char* number)
{
	int i=0;
	if(root==NULL)return true;
	trie* p=root;
	while(number[i])
	{
		p=p->erza[number[i]-'0'];
		if(p->cnt==1)return false;
		i++;
	}
	return true;
}
int n;
int main()
{
	int t,i,j;
	cin>>t;
	trie *root;
	while(t--)
	{
		bool flag=true;
		cin>>n;
		root=NULL;
		for(i=0;i<n;i++)
		{
			cin>>number[i];
			insert(root,number[i]);
		}
		for(i=0;i<n;i++)
		{
			if(pd(root,number[i]))
			{
				flag=false;
				break;
			}
		}
		if(flag)cout<<"YES\n";
		else cout<<"NO\n";
		num=0;
	}
}


猜你喜欢

转载自blog.csdn.net/yslcl12345/article/details/50700098
今日推荐