relatively simple.
#include <stdio.h>#include<string.h>#include<stdlib.h>#defineKind 96#defineMAXN 2000000structnode{Node*fail; Node*Next[kind]; intFlag; intID; voidinit () {fail=NULL; memset (Next,null,sizeof(next)); Flag=0; ID=0; }}*q[500000];node*Root;intHead,tail;Charstr[1002][ the],S[MAXN];intvis[1005];voidInsertChar*s,intc) {Node*p=root,*QQ; inti,j,len=strlen (s); for(i=0; i<len;i++) { intid=s[i]- +; if(p->next[id]==NULL) {QQ=Newnode; QQ-init (); P->next[id]=QQ; } P=p->Next[id]; } P->flag++; P->id=C;}voidBuild_ac () {inti; Node*temp,*p; Head=tail=0; Q[tail++]=Root; while(head!=tail) {P=q[head++]; for(i=0; i<kind;i++) { if(p->next[i]!=NULL) { if(p==root) P->next[i]->fail=Root; Else{Temp=p->fail; while(temp!=NULL) { if(temp->next[i]!=NULL) {P->next[i]->fail=temp->Next[i]; Break; } temp=temp->fail; } if(temp==NULL) P->next[i]->fail=Root; } q[tail++]=p->Next[i]; } } }}voidQueryChar*s) {Node*p=root,*temp; inti,j,len=strlen (s); for(i=0; i<len;i++) { intid=s[i]- +; while(p->next[id]==null&&p!=root) {P=p->fail; } P=p->Next[id]; if(p==NULL) P=Root; Temp=p; while(temp!=root&&temp->flag>0) {vis[temp->id]++; Temp=temp->fail; } }}voidFreenode (Node *root) { for(intI=0; i<kind;i++) { if(root->next[i]!=NULL) freenode (Root-Next[i]); } Free(root);}intMain () {intI,j,n; while(SCANF ("%d", &n)! =EOF) {Root=Newnode; Root-init (); memset (Vis,0,sizeof(VIS)); for(i=1; i<=n;i++) {scanf ("%s", Str[i]); Insert (str[i],i); } build_ac (); scanf ("%s", s); query (s); for(i=1; i<=n;i++) { if(vis[i]>0) printf ("%s:%d\n", Str[i],vis[i]); } freenode (root); }}
hdu3065 AC automatic Machine