Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 3741 Accepted Submission(s): 1409
Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
You are to find all the hat’s words in a dictionary.
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
Only one case.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a ahat hat hatword hziee word
Sample Output
ahat hatword
Author
戴帽子的
题意:输入单词,输出能由其他两个单词合成的单词
思路:字典树
注意:用scanf()用gets()会wa
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char s[55002][120];
struct node
{
int flag;
struct node *next[26];
};
struct node *newnode()
{
int i;
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->flag=0;
for(i=0;i<26;i++)
{
p->next[i]=NULL;
}
return p;
}
void insert(struct node *root,char *s)
{
struct node *p;
int i,len,t;
p=root;
len=strlen(s);
for(i=0;i<len;i++)
{
t=s[i]-'a';
if(p->next[t]==NULL)
p->next[t]=newnode();
p=p->next[t];
}
p->flag=1;
}
int search(struct node *root,char *s)
{
struct node *p=root;
int i,t,len;
len=strlen(s);
for(i=0;i<len;i++)
{
t=s[i]-'a';
if(p->next[t]==NULL)
return 0;
p=p->next[t];
}
if(p->flag)
return 1;
return 0;
}
void dell(struct node *p)
{
int i;
for(i=0;i<26;i++)
{
if(p->next[i]!=NULL)
dell(p->next[i]);
}
free(p);
p=NULL;
}
int main()
{
int i,j,count=0;
char str[1000];
struct node *root;
root=newnode();
while(scanf("%s",str)!=EOF)
{
strcpy(s[count++],str);
insert(root,str);
}
for(i=0;i<count;i++)
{
for(j=1;j<=(strlen(s[i])-1);j++)
{
char temp1[120]={'\0'};
char temp2[120]={'\0'};
strncpy(temp1,s[i],j);
strncpy(temp2,s[i]+j,strlen(s[i])-j);
if(search(root,temp1)&&search(root,temp2))
{
printf("%s\n",s[i]);
break;
}
}
}
dell(root);
return 0;
}