点击打开题目
Phone List
Time Limit: 1000MS | Memory Limit: 65536K | |
|---|---|---|
Total Submissions: 27567 | Accepted: 8263 |
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
98346Sample Output
NO
YESSource
Nordic 2007
分析就不多说了,看上一篇博客,说的很详细:点击打开链接
但是这个题是POJ的,数据比较厉害,动态存图会TLE(果然省时间就给费空间,省空间就得费时间)
其实静态存图就是先开一定的空间给字典树,完了往后依次取空间即可。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define idx(x) (x-'0')
bool ans;
struct Trie
{
Trie *next[10];
int v;
void init()
{
v = 0;
for (int i = 0 ; i <= 9 ; i++)
next[i] = NULL;
}
}tree[1<<16];
int ant;
void insert(char *s)
{
int l = strlen(s);
Trie *p = &tree[0], *q;
for (int i = 0 ; i < l ; i++)
{
int id = idx(s[i]);
if (p->next[id] == NULL)
{
if (p->v == -1) //若在该点有字符串结束,那么那个字符串为该串的前缀
{
ans = false;
return;
}
q = &tree[ant++];
p->next[id] = q;
}
p = p->next[id];
}
p->v = -1; //这个-1表示一个字符串已经结束
for (int i = 0 ; i < 10 ; i++)
{
if (p->next[i] != NULL)
{
ans = false; //如果该点不是叶子,则它为别的串的前缀
return;
}
}
}
void del(int n)
{
for (int i = 1 ; i < ant ; i++)
tree[i].init();
}
int main()
{
int u;
int n;
char s[15];
scanf ("%d",&u);
while (u--)
{
ans = true;
tree[0].init();
ant = 1;
scanf ("%d",&n);
for (int i = 0 ; i < n ; i++)
{
scanf ("%s",s);
if (ans)
insert(s);
else
continue; //如果之前的号码已经出现问题,那么直接继续输入就行了
}
if (ans)
printf ("YES\n");
else
printf ("NO\n");
del(ant);
}
return 0;
}