hdu1247 Hat’s Words ---- 字典树

来源:互联网 发布:佛山保险网络继续教育 编辑:程序博客网 时间:2024/06/11 20:08

原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1247


一:原题内容

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
aahathathatwordhzieeword
 
Sample Output
ahathatword


二:分析理解

题意很清楚:就是给出若干个单词,找出其中能够由其它两个单词连接组合而成的单词。比如上面sample中的"ahat"能够由"a"和"hat"拼凑而成,"hatword"="hat"+"word".因此只需对每个单词进行切分,把切分得到的两个单词在原单词序列中查找,若能查到则符合条件。在这里为了降低查找的复杂度,采用Trie树存储原始单词序列。


三:AC代码

#define _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #include<iostream>    #include<algorithm>    using namespace std;struct Node{bool word;Node* next[26];Node() { word = false; for (int i = 0; i < 26; i++)next[i] = nullptr;}};char ch[50005][55];Node* root = new Node;void insert(char* pCh){Node* p = root;while (*pCh != '\0'){if (p->next[*pCh - 'a'] == nullptr)p->next[*pCh - 'a'] = new Node;p = p->next[*pCh - 'a'];pCh++;}p->word = true;}bool findBehind(char* pCh){Node* p = root;while (*pCh != '\0'){if (p->next[*pCh - 'a'] == nullptr)return false;p = p->next[*pCh - 'a'];pCh++;}if (p->word == true)return true;return false;}bool find(char* pCh){Node* p = root;while (*pCh != '\0'){p = p->next[*pCh - 'a'];pCh++;/*if (p->word == true)return findBehind(pCh);*///有点坑啊,这里忘记了,一个单词可能包括好几个单词,所以如果findBehind返回失败,//也应该继续往下查找而不是结束该单词的判断if (p->word == true && findBehind(pCh))return true;}return false;}int main(){int c = 0;while (scanf("%s", ch[c])!=EOF){insert(ch[c++]);}for (int i = 0; i < c; i++){if (find(ch[i]))printf("%s\n", ch[i]);}return 0;}


1 0
原创粉丝点击