First road Trie
You also need to write a question to build your own code habits.
1#include <cstdio>2#include <vector>3#include <algorithm>4 #defineMAXN 200105 using namespacestd;6 7 structNode {8 Charv;9 intsz;Ten BOOLIsword, Mark; OneNode *son[ -], *Pre; A}POOL[MAXN], *tail=pool, *NULL=Pool; - - Chartemp[ -]; the structTrie { -Node *Root; -Vector<node*>Stk; -node* newnode (Node *p,Charv) { +Node *nd = + +tail; -Nd->sz =0; +Nd->v =v; ANd->isword = Nd->mark =false; atNd->pre =p; - for(intI=0; i< -; i++) Nd->son[i] =NULL; - returnnd; - } - voidInsertConst Char*str) { - if(!root) Root=newnode (NULL,'^'); inNode *nd=Root; - while(1) { to if( *str) { + if(nd->son[*str-'a']==NULL) nd->son[*str-'a']=newnode (nd,*str-'a'); -nd->sz++; thend = nd->son[*str-'a']; *str++; $}Else {Panax NotoginsengNd->isword =true; - stk.push_back (ND); the return; + } A } the } + voidMake_mark (Node *nd) { - if(nd->Isword) { $Nd->mark =true; $ for(intI=0; i< -; i++ ) - if(nd->son[i]!=NULL) Make_mark (nd->son[i]); -}Else if(nd->sz==1 ) { theNd->mark =true; -}Else {Wuyi for(intI=0; i< -; i++ ) the if(nd->son[i]!=NULL) Make_mark (nd->son[i]); - } Wu } - Char*Get(Node *BT) { About while(!bt->mark) bt=bt->Pre; $ inti; - for(i=0; Bt!=root; I++,bt=bt->pre) -Temp[i] = bt->v+'a'; -Temp[i] =0; AReverse (temp, temp+i); + returntemp; the } - voidPrint (node *nd) { $fprintf (stderr,"nd%d ch%c Mark%d\n", Nd-pool, nd->v+'a', nd->mark); the for(intI=0; i< -; i++ ) the if(nd->son[i]!=NULL) Print (nd->son[i]); the } the }t; - in voidPtChar*St) { thefprintf (stderr,"%s\n", ST); the } About Charstr[1010][ -]; the intMain () { the inti; the for(i=0; ; i++ ) { + if(SCANF ("%s", str[i])! =1 ) { -i--; the Break;Bayi } the T.insert (Str[i]); the } - for(intI=0; i< -; i++ ) - if(t.root->son[i]!=NULL ) theT.make_mark (t.root->son[i]); the for(intt=0; t<=i; t++ ) theprintf"%s%s\n", Str[t], T.Get(T.stk[t])); the}
View Code
POJ 2001 Trie