题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13822 Accepted Submission(s): 4961
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
【中文题意】问你哪个单词可以由词库中的其他单词连接组成。
【思路分析】创建一棵字典树,然后对每一个单词暴力处理就好了。
【AC代码】
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<string.h>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define maxn 50005//字典树的总层数
#define trsize 26//字典树每一层需要26个空间
struct Trie
{
int ch[maxn][trsize];
bool isEnd[maxn];
int size;
void init()
{
size=1;
memset(ch[0],0,sizeof(ch[0]));
memset(isEnd,0,sizeof(isEnd));
}
int index(char c)
{
return c-'a';
}
void insert(char *s)//插入一个单词
{
int i,rt;
for(i=rt=0; s[i]!='\0'; i++)
{
int c=index(s[i]);
if(!ch[rt][c])
{
memset(ch[size],0,sizeof(ch[size]));
ch[rt][c]=size++;
}
rt=ch[rt][c];
}
isEnd[rt]=1;
}
bool find(char *s)//查找一个单词是否存在
{
int i,rt;
for(i=rt=0; s[i]!='\0'; i++)
{
int c=index(s[i]);
if(!ch[rt][c])
return false;
rt=ch[rt][c];
}
return isEnd[rt];
}
} trie;
char s[maxn][50];//输入的单词
char str[50];//充当临时变量的作用
int main()
{
int n;
trie.init();
for(n=0; scanf("%s",s[n])!=EOF; n++)
{
trie.insert(s[n]);
}
for(int i=0; i<=n; i++)
{
int len=strlen(s[i]);
for(int j=1; j<len; j++)
{
memset(str,0,sizeof(str));
strncpy(str,s[i],j);
if(trie.find(str)&&trie.find(s[i]+j))
{
printf("%s\n",s[i]);
break;
}
}
}
return 0;
}