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
wordSample Output
ahat
hatword
题意:给出多个单词,要在这些单词中找出正好是这多个单词中另外两个单词首尾相连构成的,并按字典序输出所有找到的单词
思路:首先利用给出的单词构建字典树,然后遍历每个单词,将单词分成两段,看这两段是不是都在 Trie 中,若在则直接输出
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define E 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD=7;
const int N=100000+5;
const int dx[]= {-1,1,0,0};
const int dy[]= {0,0,-1,1};
using namespace std;
int tot;
int trie[N][50];//trie[rt][x]=tot,root是上个节点编号,x是字母,tot是下个节点编号
bool vis[N];//查询整个单词用
void insert(char *s,int root){
for(int i=0;s[i];i++){
int x=s[i]-'a';
if(trie[root][x]==0)//现在插入的字母在之前同一节点处未出现过
trie[root][x]=++tot;//字母插入一个新的位置,否则不做处理
root=trie[root][x];//为下个字母的插入做准备
}
vis[root]=true;//标志该单词末位字母的尾结点,在查询整个单词时用
}
bool find(char *s,int root){
for(int i=0;s[i];i++){
int x=s[i]-'a';
if(trie[root][x]==0)
return false;//以rt为头结点的x字母不存在,返回0
root=trie[root][x];//为查询下个字母做准备
}
return vis[root];//查询整个单词时
}
char word[N][50];
int main(){
int cnt=0;
tot=1;
while(scanf("%s",word[cnt])!=EOF)
insert(word[cnt++],1);
for(int i=0;i<cnt;i++){//枚举所有单词
int len=strlen(word[i]);
for(int j=1;j<len;j++){//拆分当前单词
char str1[50],str2[50];
strncpy(str1,word[i],j);
str1[j]=0;
strncpy(str2,word[i]+j,len-j);
str2[len-j]=0;
if(find(str1,1) && find(str2,1)){
printf("%s\n",word[i]);
break;
}
}
}
return 0;
}