问题描述:
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
ahat
hatword
大致题意:
给出若干个单词,找出其中能够由其它两个单词连接组合而成的单词。比如上面sample中的”ahat”能够由”a”和”hat”拼凑而成,”hatword”=”hat”+”word”.因此只需对每个单词进行切分,把切分得到的两个单词在原单词序列中查找,若能查到则符合条件。
思路分析:
字典树。
ac代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
#define M 50005
#define N 60
char str[M][N];
char s1[N],s2[N];
struct node
{
int flag;
node *next[26];
};
void insert(node *root,char s[])
{
int i=0,j,k;
int len=strlen(s);
node *current=root;
while(i<len)
{
k=s[i]-'a';
if(current->next[k]==NULL)
{
node *p=new node;
for(j=0;j<26;++j)
p->next[j]=NULL;
p->flag=0;
if(i==len-1)
p->flag=1; //标记最后一个字符
current->next[k]=p;
current=p;
}
else
current=current->next[k];
++i;
}
}
bool search(node *root,char s[])
{
int i=0,j,k;
int len=strlen(s);
node *current=root;
while(i<len)
{
k=s[i]-'a';
if(current->next[k]==NULL)
return false;
current=current->next[k];
i++;
}
return current->flag;
}
int main()
{
int i,j,k,cnt=0,temp,m,n;
node *root=new node;
for(i=0;i<26;++i)
root->next[i]=NULL;
root->flag=0;
while(gets(str[cnt]))
{insert(root,str[cnt]); cnt++;}
for(i=0;i<cnt;++i)
{
temp=strlen(str[i]);
for(j=1;j<temp;++j)
{
memset(s1,0,sizeof(s1));
memset(s2,0,sizeof(s2));
for(m=0;m<j;++m)
s1[m]=str[i][m];
for(n=j;n<temp;++n)
s2[n-j]=str[i][n];
if(search(root,s1)&&search(root,s2))
{ cout<<str[i]<<endl; break;}
}
}
return 0;
}