Hat’s Words
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
这个主函数有点麻烦了,哟啊把一个单词拆分n-1次,感觉有点坑了,
字典树,,
#include <iostream>
using namespace std;
char s[50001][55];
int vis[50001];
struct node
{
node *next[26];
int flag;
node()
{
memset(next,0,sizeof(next));
flag=0;
}
};
node *root=NULL;
void build(char *s)
{
node *p=root;
int i,len=strlen(s);
for(i=0;i<len;i++)
{
if(p->next[s[i]-'a']==NULL)
p->next[s[i]-'a']=new node;
p=p->next[s[i]-'a'];
}
p->flag=1;
}
int findstr(char *s)
{
node *p=root;
int i,len=strlen(s);
for(i=0;i<len;i++)
{
if(p->next[s[i]-'a']!=NULL)
p=p->next[s[i]-'a'];
else
return 0;
}
return p->flag;
}
int main()
{
root=new node;
int i=0;
char s1[55],s2[55];
while(~scanf("%s",s[i]))
{
build(s[i]);
i++;
}
int n=i,j,k,l,len;
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++)
{
len=strlen(s[i]);
if(len==1)continue;
for(j=1;j<len;j++)
{
for(k=0;k<j;k++)
s1[k]=s[i][k];
s1[k]='\0';
for(l=0;k<len;k++,l++)
s2[l]=s[i][k];
s2[l]='\0';
if(findstr(s1)&&findstr(s2))
{
vis[i]=1;
break;
}
}
}
for(i=0;i<n;i++)
{
if(vis[i])
printf("%s\n",s[i]);
}
return 0;
}