Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5664 Accepted Submission(s): 2109
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
题目大意:给出你很多单词,求哪些单词是由这里其他单词(2个)连接组成的,注意!2个相同的单词连接也可以的!
AC代码
#include<iostream>
using namespace std;
char str[50001][20];
struct node
{
int flag;
node *next[26];
node()
{
flag=0;
memset(next,0,sizeof(next));
}
};
node *root=NULL;
void build(char *s)
{
node *p=root;
int i,j;
for(i=0;s[i]!='\0';i++)
{
j=s[i]-'a';
if(p->next[j]==NULL)
p->next[j]= new node;
p=p->next[j];
}
p->flag=1;
}//建字典树
int findstr(char *s)
{
int i,j,k,f;
for(i=0;s[i]!='\0';i++)
{
node *p=root;
for(j=0;j<i;j++)
{
k=s[j]-'a';
p=p->next[k];
}//把单词拆分
if(p->flag==1)//前半部分是字典树单词
{
node *q=root;
f=1;
for(j=i;s[j]!='\0';j++)
{
k=s[j]-'a';
if(q->next[k]==NULL)
{
f=0;
break;
}
q=q->next[k];
}//判断后半部分是不是字典树单词
if(q->flag==1&&f)
return 1;
}
}
return 0;
}//查找
int main()
{
root=new node;
int i=0,j;
while(scanf("%s",str[i])!=EOF)
{
build(str[i]);
i++;
}
for(j=0;j<i;j++)
{
if(findstr(str[j]))
printf("%s\n",str[j]);
}
return 0;
}
本题为字典树!
谢谢阅读!