Typical trie tree, is to review the string bar, is the input is a bit disgusting, the code is as follows:
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intMAXN =500000+ -;structtrie{BOOLIsword; intnext[ -]; Charwords[ the]; Trie () {memset (Next,-1,sizeof(next)); Isword=false; }}root; Trie NODE[MAXN];intN;voidInsert (Char*tar) {Trie*head = &Root; Char*s =tar; while(*tar!=' ') tar++; *tar=' /'; Tar++; while(*tar!=' /'){ intid = *tar-'a'; if(Head->next[id] = =-1) {Head->next[id] = n++; } head= &node[head->Next[id]]; Tar++; } head->isword =true; //printf ("s =%s\n", s);strcpy (head->words, s);}Char*search (Char*tar) {Trie*head = &Root; while(*tar) { intid = *tar-'a'; if(Head->next[id] = =-1)returnNULL; Head= &node[head->Next[id]]; Tar++; } if(Head->isword)returnHead->words; Else returnNULL;}Charstr[ -];intMain () {n=0; while(gets (str)) {BOOLKongge =false; intLen =strlen (str); for(intI=0; i<len; i++) { if(Str[i] = =' ') {Kongge=true; Break; } } if(str[0]<'a'|| str[0]>'Z')Continue; if(Kongge) Insert (str); Else { Char*p =Search (str); if(p = = NULL) printf ("eh\n"); Elseprintf"%s\n", p); } } return 0;}
POJ 2503 trie Tree