首页 > 代码库 > HDU - 1247 - Hat’s Words (字典树!!)
HDU - 1247 - Hat’s Words (字典树!!)
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 8579 Accepted Submission(s): 3090
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
戴帽子的
题意:给定一些单词(按字典序给出), 按字典序输出所有满足条件的单词(条件为该单词由其它两个单词构成)
思路:先构造一颗字典树,,然后再依次判断该单词是否有其他两个单词组成,,判断方法为在该单词中找其中存在p->is为true的点,然后将点+1放入栈中,看是否这个点往后能组成一个其他单词,是则输出,,不是则不输出。。
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> using namespace std; const int MAX = 50005; char word[MAX][30]; struct node { bool is; struct node *next[26]; node() { is = false; memset(next, 0, sizeof(next)); } }; int insert(node *root, char *s) { int i = 0; node *p = root; while(s[i]) { if(p->next[s[i]-'a'] == NULL) p->next[s[i]-'a'] = new node; p = p->next[s[i]-'a']; i++; } p->is = true; } int search(node *root, char* s) { node *p = root; int i = 0; stack<int> t; while(s[i]) { if(p->next[s[i]-'a'] == NULL) return 0; p = p->next[s[i]-'a']; if(p->is && s[i+1]) t.push(i+1); i++; } while(!t.empty()) { bool ok = 1; i = t.top(); t.pop(); p = root; while(s[i]) { if(p->next[s[i]-'a'] == NULL) { ok = 0; break; } p = p->next[s[i]-'a']; i++; } if(ok && p->is) return 1; } return 0; } int main() { int num = 0; node* root = new node(); while(scanf("%s", word[num]) != EOF) { insert(root, word[num]); num++; } for(int i=0; i<num; i++) if(search(root, word[i])) printf("%s\n", word[i]); return 0; }
HDU - 1247 - Hat’s Words (字典树!!)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。