Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8534 Accepted Submission(s): 3072
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.
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.
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
Author
戴帽子的
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1671 1298 1800 2846 1305
解题分析:
这道题的解法就是先对字符串进行存储然后进行挑选。
模板题
代码:
#include<iostream>
#include<cstring>
#define MAXN 50002
using namespace std;
typedef struct Trie
{
Trie *next[26];
int flag;
}Trie;
Trie *root=(Trie *)malloc(sizeof(Trie));
char s[MAXN][50];
void creat(char str[])
{
int len=strlen(str);
Trie *p=root,*q;
for(int i=0;i<len;i++)
{
int x=str[i]-'a';
if(p->next[x])
{
p=p->next[x];
}
else
{
q=(Trie *)malloc(sizeof(Trie));
q->flag=0;
for(int j=0;j<26;j++)
q->next[j]=NULL;
p->next[x]=q;
p=q;
}
}
p->flag=1;
}
int find(char str[])
{
int len=strlen(str);
Trie *p=root;
for(int i=0;i<len;i++)
{
int x=str[i]-'a';
if(p->next[x])
p=p->next[x];
else
return 0;
}
return p->flag;
}
void del(Trie *root)
{
for(int i=0;i<26;i++)
{
if(root->next[i])
del(root->next[i]);
}
free(root);
}
int main()
{
for(int i=0;i<26;i++)
root->next[i]=NULL;
root->flag=0;
char t[50];
int k=0;
while(scanf("%s",t)>0)
{
strcpy(s[k++],t);
creat(t);
}
for(i=0;i<k;i++)
{
int len=strlen(s[i]);
for(int j=1;j<len;j++)
{
char t1[50],t2[50];
strcpy(t1,s[i]);
t1[j]='\0';
strcpy(t2,s[i]+j);
if(find(t1)&&find(t2))
{
puts(s[i]);
break; //输出单词后就跳出循环,以免重复输出
}
}
}
del(root);
return 0;
}