Phone List
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 33442 | Accepted: 9661 |
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:
- 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.
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
题意是打电话 如果在播出一个电话以前会打出去 就输出no else yes
就是一个字符串如果他的前面一部分 是另一个字符串 就输出 NO else YEs
刚开始思路就是sort 一下长度和字符串顺序 因为是排序过的 所以从前往后找 找到就输出 遍历到最后还未找到就 输出YES
暴力ac代码
#include <iostream> //暴力sort代码 ac
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <math.h>
using namespace std;
string s[10005];
int main()
{
int t;
scanf("%d",&t);
while(t--){
int n,flag=1;
scanf("%d",&n);
for(int i=1;i<=n;i++){
cin>>s[i];
}
sort(s+1,s+1+n);
for(int i=1;i<n;i++){
if(s[i+1].find(s[i])!=string::npos){
printf("NO\n");
flag=0;
i=n;
}
}
if(flag)printf("YES\n");
}
}
随后发现正解是字典树,用字典树写了一遍 ,但超时了,听dalao讲的需要用静态链表 =-= 我用的动态链表超时很绝望。
未ac字典树代码(动态链表)
#include <iostream> //字典树 动态链表 未ac =-=
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <math.h>
#include <queue>
using namespace std;
int digit=0,leg;
string a[10005],temp;
struct len{
bool flag;
int num;
struct len *next[10];
len(){
flag=false;
num=-1;
memset(next,0,sizeof(next));
}
}root;
void hanshu(string s){
int fuck=s.length();
leg=min(leg,fuck);
struct len *p=&root;
for(int i=0;i<fuck;i++){
if(p->next[s[i]-'0']==NULL){
p->next[s[i]-'0']=new struct len;
}
p=p->next[s[i]-'0'];
}
if(p->flag==0){
p->flag=1;
p->num=digit++;
}
}
int cha(string s){
int fuck=s.length();
struct len *p=&root;
for(int i=0;i<fuck;i++){
if(p->next[s[i]-'0']==0){
return -1;
}
p=p->next[s[i]-'0'];
}
return p->num;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
int dee=0;
int n;
struct len cmp;
root=cmp;
digit=0;
leg=1000000;
scanf("%d",&n);
for(int i=1;i<=n;i++){
cin>>a[i];
hanshu(a[i]);
}
for(int i=1;i<=n&&dee==0;i++){
int num=a[i].length();
for(int j=leg;j<num-1&&dee==0;j++){
temp=a[i].substr(0,j);
if(cha(temp)!=-1){
cout<<"NO"<<endl;
dee=1;
}
}
}
if(dee==0)cout<<"YES"<<endl;
}
}