Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8343 Accepted Submission(s): 3004
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.
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.
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a
ahat
hat
hatword
hziee
word
ahat
hat
hatword
hziee
word
Sample Output
ahat
hatword
Author
戴帽子的
简述题意: 给你很多单词,查找能够由其中的两个单词拼合而成的单词,并按字典序输出.....
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
typedef struct node
{
struct node *child[];
bool tail;
}Trie;
char mat[][];
void Insert(char *s,Trie *root)
{
int i,pos,j;
Trie *cur=root,*curnew;
for(i=;s[i]!='\0';i++){
pos=s[i]-'a';
if(cur->child[pos]==NULL)
{
curnew=(Trie *)malloc(sizeof(Trie));
for(j=;j<;j++)
curnew->child[j]=NULL;
curnew->tail=false;
cur->child[pos]=curnew;
}
cur=cur->child[pos];
}
cur->tail=true;
}
bool check(char *s,Trie *root)
{
int i,pos;
Trie *cur=root;
for(i=;s[i]!='\0';i++)
{
pos=s[i]-'a';
if(cur->child[pos]==NULL) return ;
cur=cur->child[pos];
}
if(cur->tail==)return ;
return ;
}
bool query(char *s,Trie *root)
{
int i,pos;
Trie *cur=root;
for(i=;s[i]!='\0';i++)
{
pos=s[i]-'a';
if(cur->child[pos]==NULL) return ;
else
if(cur->tail==&&check(s+i,root))
return ;
cur=cur->child[pos];
}
return ;
}
int main()
{
int i=,j;
#ifdef LOCAL
freopen("test.in","r",stdin);
#endif
Trie *root=(Trie *)malloc(sizeof(Trie));
root->tail=;
for(j=;j<;j++)
root->child[j]=NULL;
while(scanf("%s",mat[i])!=EOF){
Insert(mat[i],root);
i++;
}
for(j=;j<i;j++)
{
if(query(mat[j],root))
printf("%s\n",mat[j]);
}
return ;
}