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.
-
输入
- The first line of input gives a single integer, 1 ≤ t ≤ 10, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 100000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits. 输出
- For each test case, output "YES" if the list is consistent, or "NO" otherwise. 样例输入
-
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
样例输出
-
NO YES
**题目大意说的是给你多个电话号码,问是否有号码是另外一个号码的前缀。。
刚接触线段树也不是十分理解,网上学习,加一点自己的理解吧,可以先百度了解线段树的知识
#include<stdio.h>
#include<string.h>
const int N = 1000005;
const int ARR_SIZE = 10;
struct NODE
{
bool IsLast;//标记是不是字符串的最后一个字符
NODE *next[ARR_SIZE];
};
NODE node[N];
const int Size = ARR_SIZE * sizeof(NODE *);
bool Insert(char *str, int &top)
{
int nLen = strlen(str);
NODE *p = &node[0];
for(int i = 0; i < nLen; ++i)
{
//如果其根节点是字符串的尾节点,由题知,这里不需要考虑两个号码完全相同的情况
if(p->IsLast)
return true;
if(p->next[str[i] - '0'] == NULL)//以前不存在,加入
{
node[top].IsLast = (i == nLen - 1) ? 1 : 0;
memset(node[top].next, 0, Size);
p->next[str[i] - '0'] = &node[top];
++top;
}
else if(i == nLen - 1)//当前节点已经存在且是最后的字符了,返回
return true;
p = p->next[str[i] - '0'];
}
return false;
}
int main()
{
int t,n,i;
char str[13];
bool flag;
int top;
scanf("%d", &t);
while(t--)
{
flag = 0;
top = 1;
node[0].IsLast = 0;
memset(node[0].next, 0, Size);
scanf("%d", &n);
for(i = 0; i < n; ++i)
{
scanf("%s", str);
if(!flag)
flag = Insert(str, top);
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}