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
解题思路
用的静态数组写的,出现NO的情况有两,一是输入的字符串先短后长,长字符串会经过,之前字符串的终止节点;
二是输入的字符串先长后短,短字符串不会产生新的节点。
AC代码(1)
#include <cstdio>
#include <cstring>
int ch[100000][27], finish[100000][27]; //ch[][]记录节点编号,第几个节点经某个元素到第几个节点,finish[][]记录结束节点
int num_jd; //num_id 节点的个数
int val[100000]; //val[]记录了每个节点的分支数,本题中没用
int flag1, flag2;
void init()
{
num_jd = 1;
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
memset(finish, 0, sizeof(finish));
}
void insert(char *s)
{
int u = 0, i, c, len = strlen(s);
for(i = 0; i < len; i++)
{
c = s[i] - '0';
if(!ch[u][c])
{
ch[u][c] = num_jd++;
flag1 = 1;
}
if(finish[u][c])
flag2 = 1;
if(i == len - 1)
finish[u][c] = 1;
u = ch[u][c];
val[u]++;
}
}
int main()
{
int T, h, N;
char str[15];
scanf("%d", &T);
while(T--)
{
init();
scanf("%d", &N);
flag1 = 0, flag2 =0;
for(h = 0; h < N; h++)
{
scanf("%s", str);
if(h > 0 && !flag1 || flag2)
continue;
flag1 = 0, flag2 =0;
insert(str);
}
if(!flag1 || flag2)
{
printf("NO\n");
continue;
}
else
printf("YES\n");
}
return 0;
}
AC代码(2)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char phone[10000][15];
int cmp(const void* a,const void* b)
{
return strcmp((char*)a, (char*)b);
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int i, n;
bool flag = false;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%s", phone[i]);
}
qsort(phone, n, sizeof(phone[0]), cmp);
for(i = 0; i < n - 1; i++)
{
if(strncmp(phone[i], phone[i+1], strlen(phone[i])) == 0)
{
flag = true;
break;
}
}
if(flag == false)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}