|
Language:
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:
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;
}
}
本文介绍了一种使用字典树的方法来检查电话号码列表的一致性,确保任一号码不是另一个号码的前缀,避免呼叫冲突。
504

被折叠的 条评论
为什么被折叠?



