hdu1671(字典樹判斷字首字尾)
Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 26114 Accepted Submission(s): 8716
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.
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
2008 “Insigma International Cup” Zhejiang Collegiate Programming Contest - Warm Up(3)
Recommend
lcy | We have carefully selected several similar problems for you: 1075 1247 1800 1677 1298
判斷一個有沒有一個串是其他串的字首
插入的時候判斷這個串有沒有出現字首,是不是其他串的字首
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define maxn 100005
int ch[maxn][10];
int val[maxn];
int sz;
void init()
{
sz=0;
//val[0]=0;
memset(ch,0,sizeof(ch));
}
bool insert(char*s)
{
int u=0,n=strlen(s);
bool ok=true;
for(int i=0;i<n;i++)
{
int id=s[i]-'0';
if(ch[u][id]==0)
{
ch[u][id]=++sz;
val[sz]=0;
memset(ch[sz],0,sizeof(ch[sz]));
}
u=ch[u][id];
if(val[u]>0)
ok=false;
}
val[u]=n;
if(ok)
{for(int i=0;i<10;i++)
if(ch[u][i]!=0)
{ok=false;
break;
}
}
return ok;
}
char s[20];
int main()
{int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
init();
bool ok=true;
for(int i=0;i<n;i++)
{
scanf("%s",s);
if(ok)
ok= insert(s);
}
if(ok)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}