Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 17880 Accepted Submission(s): 5975
Problem 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:
1. Emergency 911
2. Alice 97 625 999
3. 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 97 625 999
3. 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
说一下思路:
对于出现的字符串x和y,可能x是y的前缀,可能y是x的前缀。我们假设先输入x再输入y
①x是y的前缀:输入y的时候,如果碰见字符串结束的表示(我的代码用p->v == -1)标记,那么x就是它的前缀,标记退出即可。
②y是x的前缀:当y输入完成后,检查一下p->next [ i ] (i : 0 ~ 9)如果有不等于NULL的,说明它是别的字符串的前缀,记录退出。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
bool ans;
struct Trie
{
Trie *next[10];
int v;
void init()
{
v = 0;
for (int i = 0 ; i <= 9 ; i++)
next[i] = NULL;
}
};
Trie *root;
int idx(char c)
{
return c-'0';
}
void insert(char *s)
{
int l = strlen(s);
Trie *p = root, *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 = (Trie *)malloc(sizeof(Trie));
q->init();
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(Trie *root) //不释放内存的话会MLE
{
for (int i = 0 ; i < 10 ; i++)
{
if (root->next[i] != NULL)
del(root->next[i]);
}
free(root);
}
int main()
{
int u;
int n;
char s[15];
scanf ("%d",&u);
while (u--)
{
ans = true;
root = (Trie *)malloc(sizeof(Trie));
root->init();
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(root);
}
return 0;
}