POJ 3630 trie树
Phone List
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26559 Accepted: 8000
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
题意:t个case(1<=t<=40),给你n个电话号码(电话号码长度<10)(1 ≤ n ≤ 10000),如果有电话号码是另一个电话号码的前缀,则称这个通讯录是不相容的,判断通讯录是否相容。
思路:
trie树(静态),动态分配内存会超时(最多4000000个new……)
把电话的结尾做标记,check的过程中,如果是电话号码的结尾并且trie树后面还有枝子,输出NO。(对树DFS一下)
每次新建枝子的时候要记得把枝子后面的设成初值(-1),这样就不用每个case对树DFS清零了。我开了一个l数组代表电话的长度(其实有点儿多余。)
代码实现得不好看,将就看吧。。。
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct trie
{
bool x;
int next[10];
}y[100005];
char a[10001][10],flag;
int CASE,n,l[10001],tot;
void insert(int q)
{
int p=0;
for(int i=0;i<l[q];i++)
{
if(y[p].next[a[q][i]]==-1)
{
tot++;
y[p].next[a[q][i]]=tot;
for(int i=0;i<10;i++)
y[tot].next[i]=-1;
y[tot].x=0;
p=tot;
}
else
p=y[p].next[a[q][i]];
}
y[p].x=1;
}
void check(int x)
{
for(int i=0;i<10;i++)
{
if(~y[x].next[i])
{
if(y[x].x!=y[y[x].next[i]].x)
{
for(int ii=0;ii<10;ii++)
if(~y[y[x].next[i]].next[ii]) flag=1;
check(y[x].next[i]);
}
else check(y[x].next[i]);
}
}
}
int main()
{
scanf("%d",&CASE);
while(CASE--)
{
tot=0;
for(int i=0;i<10;i++)
y[0].next[i]=-1;
flag=y[0].x=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s",a[i]);
l[i]=strlen(a[i]);
for(int j=0;j<l[i];j++)
a[i][j]-='0';
insert(i);
}
check(0);
if(flag)printf("NO\n");
else printf("YES\n");
}
}
一次AC~
这位前辈是怎么用0msAC的!!! 代码量又这么少。。佩服啊