标签:hdu1247 hats words 字典树
a ahat hat hatword hziee word
ahat hatword
#include <stdio.h> #include <string.h> #include <stdlib.h> struct Trie{ bool isWord ; Trie *next[26] ; }*root; char all[50010][100] ; void init(Trie *node) { node->isWord = false ; for(int i = 0 ; i < 26 ; ++i) { node->next[i] = NULL ; } } void insert(char s[]) { int len = strlen(s) ; Trie *t = root ; for(int i = 0 ; i < len ; ++i) { if(t->next[s[i]-'a'] == NULL) { Trie *next = (Trie *)malloc(sizeof(Trie)); init(next) ; t->next[s[i]-'a'] = next ; } t = t->next[s[i]-'a'] ; } t->isWord = true ; } bool search(char s[]) { int len = strlen(s) ; Trie *t = root ; for(int i = 0 ; i < len ; ++i) { if(t->next[s[i]-'a']) { t = t->next[s[i]-'a'] ; } else { return false ; } } if(t->isWord) { return true ; } return false ; } void del(Trie *t) { for(int i = 0 ; i < 26 ; ++i) { if(t->next[i] != NULL) { del(t->next[i]) ; } } free(t) ; } int main() { char word[100] ; root = (Trie *)malloc(sizeof(Trie)) ; init(root) ; int index = 0 ; while(gets(word) != NULL) { strcpy(all[index++],word) ; insert(word) ; } for(int i = 0 ; i < index ; ++i) { int len = strlen(all[i]) ; for(int j = 1 ; j < len ; ++j) { char a[100] , b[100] ; strncpy(a,all[i],j) ; a[j] = '\0' ; if(search(a)) { strncpy(b,all[i]+j,len-j) ; b[len-j] = '\0' ; if(search(b)) { puts(all[i]) ; break ; } } } } del(root) ; return 0 ; }
hdu 1247 Hat’s Words 字典树,还是比较有意思的题目
标签:hdu1247 hats words 字典树
原文地址:http://blog.csdn.net/lionel_d/article/details/44260763