Dictionary Tree +KMP
Reference from: http://www.cppblog.com/mythit/archive/2009/04/21/80633.html
1 Const intMAXN = -;//Dictionary size2 3 //Defining Nodes4 structnode{5node*fail;6node*CHILD[MAXN];7 intcount;8 node () {9Fail =NULL;TenCount =0; Onememset (Child, NULL,sizeof(child)); A } -}; - the //insert words into the dictionary tree - voidInsert (node* root,Char*str) { -node* p =Root; - inti =0; + while(Str[i]) { - intindex = str[i]-'a'; + if(P->child[index] = = NULL) P->child[index] =Newnode (); Ap = p->Child[index]; at++i; - } -p->count++; - } - - //BFS Construction mismatch pointer/build Acautomation in //constructor Sub-node mismatch pointer by current node - voidBuild_acautomation (node*root) { toQueue<node*>Q; +Root->fail =NULL; - Q.push (root); the while(!Q.empty ()) { *node* temp =Q.front (); $node* p =NULL;Panax Notoginseng for(inti =0; i < MAXN; ++i) { - if(Temp->child[i]! =NULL) { the if(temp = = root) Temp->child[i]->fail =Root; + Else{ Ap = temp->fail; the while(P! =NULL) { + if(P->child[i]! =NULL) { -Temp->child[i]->fail = p->Child[i]; $ Break; $ } -p = p->fail; - } the if(p = = NULL) Temp->child[i]->fail =Root; - }WuyiQ.push (temp->child[i]); the } - } Wu } - } About $ //acautomation Matching - //computes the number of strings and their suffix substrings currently being matched - //count varies by topic - intQuery (node*root) { A inti =0, cnt =0, index; +node* p =Root; the while(Str[i]) { -index = str[i]-'a'; $ while(P->child[index] = = NULL && p! = root) p = p->fail; thep = p->Child[index]; thep = (p = = NULL?)root:p); thenode* temp =p; the while(Temp! = root && temp->count! =-1){ -CNT + = Temp->count; inTemp->count =-1; thetemp = temp->fail; the } About++i; the } the returnCNT; the}
Continue to learn ..... Prepare to do the title (VJ kuangbin AC automata special topic)
AC Automaton (AC automation)