C++——字典树(Trie树)例题——Phone List(POJ3630)(HDU1671)

Phone List

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 28678 Accepted: 8612

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.

给出一份电话号码列表,如果不存在有一个号码是另一个号码的前缀,我们就说这份电话号码列表是合法的。让我们看看如下号码列表:
1. Emergency  911
2. Alice  97625999
3. Bob  91125426
在这组号码中,我们不能拨通 Bob 的电话,因为当你按下 Bob 电话号码的前 3 个数字“911”时,电话局会把你的拨号连接到 Emergency 的线路。
所以这组号码是不合法的。

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.

有多组输入数据。
第一行输入一个正整数 t(1<=t<=40),表示数据组数。
每组数据第一行是一个正整数 n(1<=n<=10000),表示电话号码的数量。
接下来有 n 行,每行一个电话号码,每个电话号码是不超过 10 位的连续数字。

Output

For each test case, output “YES” if the list is consistent, or “NO” otherwise.

对每组数据,如果电话号码列表合法,则输出“YES”,不合法则输出“NO”。

Sample Input

2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output

NO
YES

Source

Nordic 2007

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstdlib>
using namespace std;
const int N=1e5+5;
const int Z=10;
int tt,n,tot;
char s[20];
struct node{
	int trans[Z];
	bool bo;
	void clear()
	{
		memset(trans,0,sizeof(trans));
		bo=false;
	}
}tr[N];
bool insert(char*s)
{
	int len=strlen(s);
	int u=1;
	bool flag=false;
	for(int i=0;i<len;++i)
	{
		if(!tr[u].trans[s[i]-48])
			tr[tr[u].trans[s[i]-48]=++tot].clear();
		else if(i==len-1)
			flag=true;
		u=tr[u].trans[s[i]-48];
		if(tr[u].bo) flag=true;
	}
	tr[u].bo=true;
	return flag;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cin>>tt;
	while(tt--)
	{
		cin>>n;
		tr[tot=1].clear();
		bool ans=false;
		for(int i=1;i<=n;++i)
		{
			cin>>s;
			if(insert(s)) ans=true;
		}
		if(!ans) puts("YES");
		else puts("NO");
	}
	return 0;
}

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