Hat’s Words HDU - 1247 字典树

时间:2023-03-09 01:40:20
Hat’s Words HDU - 1247  字典树

题意:给出数个单词 输出单词 如果该单词 是由字典中的单词组成的

思路:字典树 先把全部建树  然后对于每一个单词进行分割,分别拿两半到字典树里面去找

小心RE!

 #include<bits/stdc++.h>
#include<string>
using namespace std;
const int maxn=+;
struct Trie{
int ch[maxn][];
int size;
bool num[maxn];
void init(){
memset(ch,,sizeof(ch));
memset(num,,sizeof(num));
size=;
}
void insert(char*s){
int i=,rc=;
for( ;s[i]!='\0';i++){
int id=s[i]-'a';
if(ch[rc][id]==){
ch[rc][id]=size++;
}
rc=ch[rc][id];
}
num[rc]=;
}
bool find(char*s){
int i=,rc=;
for(;s[i]!='\0';i++){
int id=s[i]-'a';
if(ch[rc][id]==){
return ;
}
rc=ch[rc][id];
}
return num[rc];
} }trie;
char temp[][];
char s1[],s2[];
int main(){
int n=;
trie.init();
while(scanf("%s",temp[n])==){
//cout<<1<<endl;
n++;
trie.insert(temp[n-]);
}
for(int i=;i<n;i++){
int len=strlen(temp[i]);
for(int j=;j<len-;j++){
for(int k=;k<j;k++){
s1[k]=temp[i][k];
}
s1[j]='\0';
for(int k=j;k<len;k++)s2[k-j]=temp[i][k];
s2[len-j]='\0';
if(trie.find(s1)&&trie.find(s2)){
printf("%s\n",temp[i]);
break;
}
}
}
return ;
}