Phone List
http://acm.hdu.edu.cn/diy/contest_showproblem.php?cid=12654&pid=1005
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 7 Accepted Submission(s) : 2
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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
Output
Sample Input
2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
Sample Output
NO YES
//这题数据量较大用strncpy()和strcmp()肯定会超时,用静态的字典树比较好
#include<iostream>
#include<cstring>
using namespace std;
struct trie{
bool end; //判断是否是某一串的终点
trie *child[10];
void init(){
end=false;
for(int i=0; i<10;i++)
child[i]=NULL;
}
}node[1000000];
int cnt;
bool insert(char *source){
trie *current=&node[0]; //根结点
for(int i=0;source[i]!='\0';i++){
if(current->child[source[i]-'0']==NULL){
current->child[source[i]-'0']= &node[++cnt];
current=current->child[source[i]-'0'];
current->init();
}
else{
current=current->child[source[i]-'0'];
if(!source[i+1]) return false;
if(current->end==true) return false;
}
if(!source[i+1]) current->end=true;
}
return true;
}
int main(){
int t,n;
char str[11];
for(cin>>t;t--;){
cnt=0;
bool flag=true;
node[0].init();
for(cin>>n;n--;){
cin>>str;
if(flag) flag=insert(str);
}
puts(flag ? "YES":"NO");
}
//system("pause");
return 0;
}
一个学期后再贴个代码吧
#include<iostream>
#include<cstring>
using namespace std;
class trie{
public:
trie(){
for(int i=0;i<10;i++)
child[i]=NULL;
end=false;
}
class trie *child[10];
bool end; //结束点
};
trie *root;
int insert(char *source){
int len=strlen(source);
if(len==0)
return 0;
trie *current,*newnode;
current=root;
for(int i=0;i<len;i++){
if(current->child[source[i]-'0']!=NULL){
current=current->child[source[i]-'0'];
if(current->end) //是另一个串的结束点
return 0;
if(source[i+1]=='\0') //下一点就是该串的结束的
return 0;
}
else{
newnode=new trie;
current->child[source[i]-'0']=newnode;
current=newnode;
}
}
current->end=true;
return 1;
}
void destroy(trie *t){ //释放内存,内存超出限制咯,纠结
if(t==NULL)
return ;
for(int i=0;i<10;i++){
if(t->child[i])
destroy(t->child[i]);
}
delete t; //这步必须加,否则无法释放内存
t=NULL; //为了保险加上这个
}
int main(){
int t,n;
scanf("%d",&t);
char ch[11];
while(t--){
root=new trie;
scanf("%d",&n);
int flag=1;
for(int i=0;i<n;i++){
scanf("%s",ch);
if(flag) flag=insert(ch);
}
if(flag)
puts("YES");
else
puts("NO");
destroy(root);
}
//system("pause");
return 0;
}