Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 12933 Accepted Submission(s): 4402
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<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
char word[10010][20];
struct Tree
{
int num;//判断此节点是否为空的(就是一棵树的结束点)
Tree *next[10];//这个是这棵树的子节点
Tree()
{
num=0;
for(int i=0;i<10;i++)
{
next[i]=NULL;
}
}//这是一棵树
}*root;//建立一个树根
int count1;
void insert(Tree *p,char *s)
{
int i=0;
while(s[i])//当这个字符串的某一个元素不为空的时候
{
int x=s[i]-'0';//看这个元素在哪里?
if(p->next[x]==NULL)//然后看这棵树有没有这个元素如果没有
{
p->next[x]=new Tree();//就在这棵树的此节点重新建立一棵子树
}
p=p->next[x];//p指向他的子树,这一点你就可以知道了所有字符串的元素原来他们都是主仆关系没有相同的等级关系!
i++;//继续遍历
}
p->num++;
}//插入字符
int find(Tree *p,char *s)
{
int i=0,ans=0;//寻找树的元素,ans是结果!
while(s[i])//当他不为空的时候就是字符串还有的时候
{
int n=s[i]-'0';//找到他在这个树的节点
if(p->next[n])//如果节点不为空
{
p=p->next[n];//p就指向该节点
ans=p->num;//结果应该为1
i++;
}
else
{
return 0;
}
}
return ans;
}
int deltree(Tree* T)
{
int i;
if(T==NULL)
return 0;
for(i=0;i<10;i++)
{
if(T->next[i]!=NULL)
deltree(T->next[i]);
}
free(T);
return 0;
}
int main()
{
int t,n,i,flag,stl,j,k;
cin>>t;
while(t--)
{
flag=0;
scanf("%d%*c",&n);
root=new Tree();
for(i=1;i<=n;i++)
{
memset(word[i],0,sizeof(word[i]));
}
for(i=1;i<=n;i++)
{
gets(word[i]);
insert(root,word[i]);
}
for(i=1;i<=n;i++)
{
stl=strlen(word[i]);
// cout<<"stl="<<stl<<endl;
for(j=0;j<stl-1;j++)
{
char s1[20];
for(k=0;k<=j;k++)
{
s1[k]=word[i][k];
}
s1[k]='\0';
// cout<<"s1="<<s1<<endl;
if(find(root,s1))
{
flag=1;
break;
}
}
if(flag==1)
{
cout<<"NO"<<endl;
break;
}
}
if(flag==0)
{
cout<<"YES"<<endl;
}
deltree(root);
}
}