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
简单的模板题
这道题如果用动态指针写不释放内存,会爆内存
#include<cstdio>
#include<iostream>
using namespace std;
struct Trie
{
int num;
Trie* next[11];
Tire()
{
for(int i=0;i<=10;i++)
next[i]=NULL;
num=0;
}
};
Trie* tree=0;
char str[10000][11]={0};
void insert1(char ctr[])
{
Trie *p=tree;
for(int i=0;ctr[i];i++)
{
int t=ctr[i]-'0';
if(p->next[t]==NULL)
p->next[t]= new Trie();
p=p->next[t];
p->num++;
}
}
int find1(char ctr[])
{
Trie *p=tree;
for(int i=0;ctr[i];i++)
{
int t=ctr[i]-'0';
if(p->next[t]==NULL)
return 0;
p=p->next[t];
}
return p->num;
}
void deletetrie(Trie* p){
for(int i=0;i<10;i++){
if(p->next[i]!=0){
deletetrie(p->next[i]);
}
}
delete p;
}
int main()
{
int t,n;
char ctr[1000]={0};
cin>>t;
while(t--)
{
tree=new Trie();
cin>>n;
int i=0,flag=0,m=n;
while(n--)
{
cin>>str[i];
insert1(str[i]);
i++;
}
for(int i=0;i<m;i++)
{
if(find1(str[i])>=2)
{
flag=1;
break;
}
}
if(flag){
printf("NO\n");
}
else printf("YES\n");
deletetrie(tree);
}
return 0;
}
用静态数组写不用担心内存问题
#include<bits/stdc++.h>
using namespace std;
int trie[100005][11];
int num[100005];
int pos=0;
char str[10005][11];
void insert1(char ctr[])
{
int c=0;
int l=strlen(ctr);
for(int i=0;i<l;i++)
{
int t=ctr[i]-'0';
if(trie[c][t]==0)
trie[c][t]=++pos;
c=trie[c][t];
num[c]++;
}
}
int find1(char ctr[])
{
int c=0;
int l=strlen(ctr);
for(int i=0;i<l;i++)
{
int t=ctr[i]-'0';
if(trie[c][t]==0)
return 0;
c=trie[c][t];
}
return num[c];
}
int main()
{
std::ios::sync_with_stdio(false);
int t,n;
cin>>t;
while(t--)
{
memset(trie,0,sizeof(trie));
memset(num,0,sizeof(num));
cin>>n;
int i=0,flag=0,m=n;
pos=0;
while(n--)
{
cin>>str[i];
insert1(str[i]);
i++;
}
for(int i=0;i<m;i++)
{
if(find1(str[i])>=2)
{
flag=1;
break;
}
}
if(flag){
printf("NO\n");
}
else printf("YES\n");
}
return 0;
}