trie树练习 Hat’s Words

来源:互联网 发布:三星电话交换机编程 编辑:程序博客网 时间:2024/06/06 08:33

Hat’s Words

TimeLimit: 2000/1000 MS(Java/Others)    MemoryLimit: 65536/32768 K (Java/Others)
Total Submission(s):2174    AcceptedSubmission(s): 791


Problem Description
A hat’s word is a word in the dictionary that is the concatenationof exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
 

Input
Standard input consists of a number of lowercase words, one perline, in alphabetical order. There will be no more than 50,000words.
Only one case.
 

Output
Your output should contain all the hat’s words, one per line, inalphabetical order.
 

Sample Input
ahat 
hat 
hatword 
hziee 
word
 

Sample Output
ahat 
hatword
#include<stdio.h>
#include<string.h>
#include<malloc.h>
 struct node
{
intflag;
struct node*next[26];
};
struct node*root;
chars[50001][21];
 struct node *chuangjian()
 {
inti;
struct node*p;
p=(structnode*)malloc(sizeof(struct node));
p->flag=0;
for(i=0;i<26;i++)
p->next[i]=NULL;
returnp;
 }
 void insert(char *s)
 {
inti;
struct node*p;
p=(structnode*)malloc(sizeof(struct node));
p->flag=0;
p=root;
intlen=strlen(s);
for(i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
{
p->next[s[i]-'a']=chuangjian();
}
p=p->next[s[i]-'a'];
}
p->flag=1;
 }
 int  search(char*s)
 {
inti,n;
n=strlen(s);
struct node*p=root;
for(i=0;i<n;i++)
{
if(p->next[s[i]-'a']==NULL)
return0;
elsep=p->next[s[i]-'a'];
}
returnp->flag;
 }
 int main()
 {
intn,i,k,m,j;
charstr1[21],str2[21];
root =(structnode*)malloc(sizeof(struct node));
    for(i=0;i<26;i++)
  root->next[i]=NULL;
k=1;
while(scanf("%s",s[k])!=EOF)
{
insert(s[k]);
k++;
}
for(i=1;i<k;i++)
{
n=strlen(s[i]);
for(j=1;j<n;j++)
{
for(m=0;m<j;m++)//一点点分来测试
str1[m]=s[i][m];
str1[m]='\0';//一定要加上,不然WA
if(search(str1))
{
intp;
for(p=j;p<n;p++)
str2[p-j]=s[i][p];
str2[p-j]='\0';
if(search(str2))
{
printf("%s\n",s[i]);
break;
}
}
}
}
free(root);
return0;
 }






 
原创粉丝点击