Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 11787 Accepted Submission(s): 4010
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
题目大意:判断给出的字符串是否存在一个字符串是另一个字符串的情况
题目分析:先将字符串按长度排序,然后每次添加一个串,将末尾的节点标记,然后之后每插入一个串的路径中碰到已经标记的串的话,就是存在题设情况,否则不存在
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 10007
using namespace std;
int t,n;
bool flag;
struct String
{
char s[12];
bool operator < ( const String& x ) const
{
return strlen(s) < strlen(x.s);
}
}a[MAX];
struct Node
{
Node* b[11];
int flag;
}node[MAX*17];
int cc;
int main ( )
{
scanf ( "%d" , &t );
while ( t-- )
{
for ( int i = 0 ; i <= cc ; i++ )
{
memset ( node[i].b , 0 ,sizeof ( node[i].b ) );
node[i].flag = 0;
}
cc = 0;
flag = true;
scanf ( "%d" , &n );
for ( int i = 1 ; i <= n ; i++ )
scanf ( "%s" , a[i].s );
sort ( a+1 , a+n+1 );
for ( int i = 1 ; i <= n; i++ )
{
Node * root = &node[0];
//scanf ( "%s" , s );
int len =strlen( a[i].s );
for ( int j = 0; j < len; j++ )
{
if ( !(root->b[a[i].s[j]-48] ) )
root->b[a[i].s[j]-48] = &node[++cc];
root = root->b[a[i].s[j]-48];
if ( root->flag ) flag = false;
}
root->flag = true;
}
if ( flag ) puts ( "YES" );
else puts ( "NO" );
}
}