a ahat hat hatword hziee word
ahat hatword
题意:给定一些单词(按字典序给出), 按字典序输出所有满足条件的单词(条件为该单词由其它两个单词构成)
思路:先构造一颗字典树,,然后再依次判断该单词是否有其他两个单词组成,,判断方法为在该单词中找其中存在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 (字典树!!)
原文地址:http://blog.csdn.net/u014355480/article/details/42212365