POJ 3630 Phone List

本文介绍了一种使用字典树的方法来检查电话号码列表的一致性,确保任一号码不是另一个号码的前缀,避免呼叫冲突。

Language:
Phone List
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26703 Accepted: 8040

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


【题目分析】

    首先想到的办法是字典树,然后判断每一个字符串的最后一个点是不是在别的字符串的路径上,如果是,那么就不行。但是这样的话还需要排序nlogn+nl被常数卡了。然后我记录每一个节点是否有结束的字符串。这样就可以不用排序了,典型的空间换时间。然后还是各种RE,TLE,用C++提交就过了。最后的最后,看了poj讨论区里的内容,才知道暴力就可以过,瞬间爆炸。


#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
struct node{
	int v;
	int end;  //0无 1 有 
};
int ans;
int trie[100001][10];
node pos[100001];//每一个节点的信息 别问我为什么要记录当前节点的内容 其实可以删 但是我有空间任性 
string s,ss[10001];
int t=0;
int sum=1;//总共的节点数 
int cmp(string a,string b)
{
	return a>b;
}
void insert(string s)//插入字符串 字典树构建过程 
{
	int pp=1;
	pos[1].v++;
	for (int i=0;i<s.size();++i){
		if (i==s.size()-1&&trie[pp][s[i]-'0']!=0){ans=1;return ;}
		if (pos[trie[pp][s[i]-'0']].end==1) {ans=1;return ;}
		if (trie[pp][s[i]-'0']!=0){
			pp=trie[pp][s[i]-'0'];
			pos[pp].v++;
		}
		else if (trie[pp][s[i]-'0']==0){
			trie[pp][s[i]-'0']=++sum;
			pos[sum].v++;
			pp=sum;
			if (i==s.size()-1) pos[pp].end=1;
		}
	}
}
int main()
{
    cin.sync_with_stdio(false);
	int n;
	scanf("%d",&n);
	while (n--){
		memset(trie,0,sizeof(trie));
		memset(pos,0,sizeof(pos));
		sum=1;
		int m;
		ans=0;
		scanf("%d",&m);
	    for (int i=1;i<=m;++i){
	    	cin>>ss[i];
	    }
	    for (int i=1;i<=m;i++){
	    	insert(ss[i]);
	    }
	    if (ans==1) cout<<"NO"<<endl;
	    else cout<<"YES"<<endl;
    }
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值