hdu 1247 Hat’s Words 字典树,还是比较有意思的题目

#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 字典树,还是比较有意思的题目

相关文章:

你感兴趣的文章:

标签云: