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. You are to find all the hat’s words in a dictionary.
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 wordSample Output
ahat hatword
题意:是否有两个字符串能合成其中一个字符串,输出能合成的字符串。
思路:两个字符串能合成一个,反过来想,一个字符串如果分成两个串在字典中存在,就成立。
#include<algorithm>
#include<string.h>
#include<stdio.h>
#define M 50010
using namespace std;
char str[M][60];
char sp1[60],sp2[60];
struct trie
{
int v;
trie *next[26];
};
trie root;
void create_Trie(char *ca)
{
trie *p=&root,*q;
while(*ca)
{
int di=*ca-'a';
if(p->next[di]==NULL)
{
q=(trie *)malloc(sizeof(trie));
for(int i=0;i<26;i++)
{
q->next[i]=NULL;
}
q->v=0;
p->next[di]=q;
}
p=p->next[di];
ca++;
}
p->v++;
}
int find_Trie(char *ca)
{
trie *p=&root;
while(*ca)
{
int di=*ca-'a';
if(p->next[di]==NULL)
{
return false;
}
p=p->next[di];
ca++;
}
return p->v;
}
int main()
{
int cut=0;
while(~scanf("%s",str[cut]))
{
create_Trie(str[cut++]);
}
int j,len,k;
for(int i=0;i<cut;i++)
{
len=strlen(str[i]);
for(j=1;j<len;j++)
{
for(k=0;k<j;k++)
{
sp1[k]=str[i][k];
}
int l=0;
sp1[k]='\0';
for(;k<len;k++)
{
sp2[l++]=str[i][k];
}
sp2[l]='\0';
if(find_Trie(sp1)&&find_Trie(sp2))
{
printf("%s\n",str[i]);
break;
}
}
}
}