题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3530
字典树,先离线接收所有串并建立字典树,然后再查询,每次查询到前面部分是单词再查询后面是不是单词,满足条件输出!
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define maxn 100000
struct trie{
trie *next[26];
bool is_word;
}po[maxn];
int pos=1;
char word[51000][20];
int insert_trie(trie *root,char *name){
if(name[0]==0){
root->is_word=true;return 0;
}
int ch=name[0]-'a';
if(root->next[ch])
insert_trie(root->next[ch],name+1);
else{
root->next[ch]=&po[pos++];
insert_trie(root->next[ch],name+1);
}
return 0;
}
bool query(trie *root,char *name){
if(name[0]==0){
return root->is_word;
}
if(root->next[name[0]-'a']==NULL)
return false;
return query(root->next[name[0]-'a'],name+1);
}
bool find_ans(trie *root,char *name){
if(name[0]==0) return false;
if(root->is_word){
if(query(&po[0],name)) return true;
}
return find_ans(root->next[name[0]-'a'],name+1);
}
int main(){
int i=0,j,k;
while(scanf("%s",word[i])!=EOF)insert_trie(&po[0],word[i++]);
for(j=0;j<i;j++){
if(find_ans(&po[0],word[j])) printf("%s\n",word[j]);
}
return 0;
}