Hat’s Words
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<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<utility>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define maxn 50005
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair<int,int>
using namespace std;
int tree[maxn][26];
int idx(char c){return c-'a';}
int tot = 1;
bool is_word[maxn];
void Insert(char s[],int u) //插入字符串s
{
for(int i=0;s[i];++i){
int c = idx(s[i]);
if(!tree[u][c])
tree[u][c] = ++tot;
u = tree[u][c];
}
is_word[u] = true; //标记这个单词结束
}
bool Find(char s[],int u) //查询s是否是前缀
{
for(int i=0;s[i];++i){
int c = idx(s[i]);
if(!tree[u][c])
return false;
u = tree[u][c];
}
return is_word[u];
}
char s[maxn][20],ns[20];
int main()
{
int n = 0;
while(scanf("%s",s[n])!=EOF){
Insert(s[n++],1);
}
for(int i=0;i<n;++i){
for(int j=1;s[i][j];++j){
memcpy(ns,s[i],sizeof(s[i])); //将s[i]复制到ns中
ns[j] = 0;
if(Find(ns,1)&&Find(s[i]+j,1)){ //s[i]+j:从s[i]的第j个开始
//将s分成两部分进行分别查找
printf("%s\n",s[i]);
break;
}
}
}
return 0;
}