Title: http://acm.hdu.edu.cn/showproblem.php?pid=2222
AC Automaton Template problem
1#include <stdio.h>2#include <string.h>3#include <queue>4 using namespacestd;5 Charkey[ -];6 Chardes[1111111];7 structnode{8Node *fail;9Node *next[ -];Ten intCNT; One node () { AFail =NULL; -CNT =0; - for(inti =0;i< -; i++) theNext[i] =NULL; - } - }; -Node *Root; + voidInsertChar*str) { -Node *head =Root; + intLen =strlen (str); A for(inti =0; i<len;i++){ at inttemp = str[i]-'a'; - if(Head->next[temp] = =NULL) -Head->next[temp] =Newnode (); -Head = head->Next[temp]; - } -head->cnt++; in } - voidbuild () { toQueue<node *>Q; + Q.push (root); - while(!Q.empty ()) { theNode *head =Q.front (); * Q.pop (); $ for(inti =0;i< -; i++){Panax Notoginseng if(Head->next[i]! =NULL) { - if(Head = =root) { theHead->next[i]->fail =Root; +}Else{ ANode *temp = head->fail; the while(Temp! =NULL) { + if(Temp->next[i]! =NULL) { -Head->next[i]->fail = temp->Next[i]; $ Break; $ } -temp = temp->fail; - } the if(temp = =NULL) -Head->next[i]->fail =Root;Wuyi } theQ.push (head->next[i]); - } Wu } - } About } $ intquery () { - intLen = strlen (des), ans =0;; -Node *head =Root; - for(inti =0; i<len;i++){ A intindex = des[i]-'a'; + while(Head->next[index] = = NULL && head! =root) theHead = head->fail; -Head = head->Next[index]; $ if(Head = =NULL) theHead =Root; theNode *temp =head; the while(Temp!=root && temp->cnt!=-1){ theAns + = temp->CNT; -temp->cnt =-1; intemp = temp->fail; the } the } About returnans; the } the intMain () { the intT; +scanf"%d",&t); - while(t--){ theRoot =Newnode ();Bayi intN; thescanf"%d",&n); the for(inti =0; i<n;i++){ -scanf"%s", key); - Insert (key); the } the build (); thescanf"%s", des); theprintf"%d\n", query ()); - } the return 0; the}
HDU 2222 AC Automaton template problem