HDU 1247-Hat’s Words(trie树)

来源:互联网 发布:声音转换器软件 编辑:程序博客网 时间:2024/06/09 22:05
D - Hat’s Words
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 1247
Appoint description: 

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

aahathathatwordhzieeword
 

Sample Output

ahathatword
思路:
这题的做法不错,一开始不懂题意,一直Wa,结果就是找只有另外两个单词组成的单词。
AC代码:
/*这题一开始就写对了,结果过了样例还是Wa了,弄了几组数据也过了,但还是Wa了,之后又弄了一组数据就没答案了。最后发现原来是v数组写了26,害我一直Wa。数据:aahathathatwordhzieewordhatwordwordaahataahatword*/#include<iostream>#include<algorithm>#include<cstring>#include<cstdio>#include<vector>#include<queue>#include<cmath>typedef long long ll;using namespace std;#define T 55555#define maxn 26#define inf 0x3f3f3f3fstruct trie{int kid[T][26],v[T];int L,root;trie(){L=1;root = 0;memset(kid[0],-1,sizeof(kid[0]));}int newnode(){v[L] = 0;memset(kid[L],-1,sizeof(kid[L]));return L++;}void insert(char* s){int p = root;for(int i=0;s[i];++i){int d = s[i] - 'a';if(kid[p][d]==-1){kid[p][d] = newnode();}p = kid[p][d];}v[p]++;}bool find(char *s){int p = 0;for(int i=0;s[i];++i){int d = s[i]-'a';p = kid[p][d];if(p==-1)return false;if(v[p]&&s[i+1]=='\0')return true;}return false;}bool query(char* s){int p = root,sum=0;for(int i=0;s[i];++i){int d = s[i]-'a';p = kid[p][d];if(v[p]&&find(s+i+1)){                 return true;}}return false;}}tr;char str[T][1000];int main(){#ifdef zsc freopen("input.txt","r",stdin);#endif int n=0,i; while(~scanf("%s",&str[n])){ tr.insert(str[n++]); } for(i=0;i<n;++i){ if(tr.query(str[i])){ printf("%s\n",str[i]); } }    return 0;}


0 0