HDU-1247-Hats Words
Http://acm.hdu.edu.cn/showproblem.php? Pid = 1, 1247
In the dictionary tree, you can divide each word into two words to see if both words are in the dictionary tree.
Note that there is a slight difference between the creation time and the previous time. When inserting a word, you only need to record the node at the end of the word and do not need to record all the prefixes of a word.
# Include <iostream> # include <cstdio> # include <cstring> # include <cstdlib> using namespace std; char word [50005] [20]; struct node {int count; node * childs [26]; node () {count = 0; int I; for (I = 0; I <26; I ++) childs [I] = NULL ;}; node * root = new node; node * current, * newnode; void insert (char * str) {int I, m; current = root; for (I = 0; I <strlen (str); I ++) {m = str [I]-'A '; if (current-> childs [m]! = NULL) current = current-> childs [m]; else {newnode = new node; current-> childs [m] = newnode; current = newnode ;}} current-> count = 1;} int search (char * str) // In the dictionary tree, find whether a word exists {int I, m; current = root; for (I = 0; I <strlen (str); I ++) {m = str [I]-'A '; if (current-> childs [m] = NULL) return 0; current = current-> childs [m];} return current-> count;} int main () {int I, j, t = 0, len; char s1 [20], s2 [20]; while (scanf ("% s", word [t])! = EOF) {insert (word [t]); t ++;} for (I = 0; I <t; I ++) {len = strlen (word [I]); for (j = 1; j <len; j ++) // divides words into two parts {strncpy (s1, word [I], j); s1 [j] = '\ 0'; // I forgot to add this sentence at the beginning. I didn't output it for half a day during debugging .. Strncpy (s2, word [I] + j, len-j); s2 [len-j] = '\ 0'; if (search (s1) & search (s2) {printf ("% s \ n", word [I]); break ;}} return 0 ;}