Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 14599 Accepted Submission(s): 5214
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.
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.
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
Author
戴帽子的
思路:先将所有单词存到字典树里,再遍历每个单词,看能不能有两个组成。
# include <iostream> # include <cstdio> # include <cstring> # define maxn 50000 using namespace std; int n=0, cnt=0; char s[maxn+3][20]; struct node { int next[27], tag; }tri[maxn+100]={0}; void add(char *s) { int len = strlen(s), pos=0; for(int i=0; i<len; ++i) { int t = s[i]-'a'; if(!tri[pos].next[t]) tri[pos].next[t] = ++cnt; pos = tri[pos].next[t]; } tri[pos].tag = 1;//tag为1表示存在以pos的节点结尾的单词。 } bool query(char *s) { int len = strlen(s), pos=0; for(int i=0; i<=len ;++i) { int t = s[i]-'a'; if(tri[pos].next[t]) { pos = tri[pos].next[t]; if(tri[pos].tag) { int pos2 = 0, j=-1; for(j=i+1; j<len; ++j) { int t2 = s[j]-'a'; if(!tri[pos2].next[t2]) break; pos2 = tri[pos2].next[t2]; if(j == len-1 && tri[pos2].tag) return true; } } } else return false; } return false; } int main() { while(~scanf("%s",s[++n])) add(s[n]); for(int i=1; i<=n; ++i) if(query(s[i])) printf("%s\n",s[i]); return 0; }