A given n pattern string appears in the main string in a few
#include <cstdio>#include<cstring>Const intmaxpt=500007;//Maximum number of nodesConst intSize= -;//number of child nodesConst Charstart='a';//child node label correspondence relationship classac_automat{Private: structNode {node*fail; Node*Next[size]; intCnt//various uses: counting, marking, etc. BOOLFlag//does the word end voidNewNode ()//Build Node{fail=NULL; for(intI=0; i<size;i++) Next[i]=NULL; CNT=0; Flag=false; } }; Node*q[maxpt],h[maxpt],*Root; intfr,tl,t; Public: voidInit () {FR= TL =0; T=0; H[t].newnode (); Root= &h[t++]; } voidInsert (Char*s) {intLen =strlen (s); Node*p =Root; for(intI=0; i<len;i++) { intK = S[i]-start; if(P->next[k] = =NULL) {H[t].newnode (); P->next[k] = &h[t++]; } P= p->Next[k]; } P->cnt++; P->flag=true; } voidBuild () {root->fail =NULL; Q[TL]=Root; while(Fr <=TL) {Node*tmp = q[fr++]; Node*p =NULL; for(intI=0; i<size;i++)if(tmp->Next[i]) { if(TMP = =root) tmp->next[i]->fail =Root; Else{p= tmp->fail; while(P! =NULL) { if(p->Next[i]) {tmp->next[i]->fail = p->Next[i]; Break; } P= p->fail; } if(p = =NULL) TMP->next[i]->fail =Root; } q[++TL] = tmp->Next[i]; } } } intQuery (Char*s) {intres =0; Node*p =Root; intLen =strlen (s); for(intI=0; i<len;i++) { intK = S[i]-start; while(P->next[k] = = NULL && P! =root) P= p->fail; P= p->Next[k]; if(p = = NULL) p =Root; Node*tmp =p; while(tmp! = root && tmp->cnt! =-1)//modified with different query requirements{res+ = Tmp->CNT; TMP->cnt =-1; TMP= tmp->fail; } } returnRes; }}ac;Charstr[1000005],s[ -];intMain () {intT,i,n; scanf ("%d",&T); while(t--) {scanf ("%d",&N); Ac. Init (); for(i=1; i<=n;i++) scanf ("%s", s), AC. Insert (s); scanf ("%s", str); Ac. Build (); printf ("%d\n", AC. Query (str)); } return 0;}
AC Automatic Machine