现在正在学ac自动机,找了些资料看了下,其实也没有那么难,先多做些题,熟悉之后再写个专题 这个题是一个裸的ac自动机,多敲敲,熟悉熟悉代码。 /* * File: main.cpp * Author: Mi * * Created on 2011年3月31日, 下午5:14 */ #include <cstdlib> #include <stdio.h> #include <string.h> #define KIND 26 #define MAX 500005 using namespace std; /* * */ char msg[MAX*20]; struct node { node *fail; node *next[KIND]; bool isword; int cnt; node() { fail=NULL; memset(next,NULL,sizeof(next)); isword=false; cnt=0; } }*que[MAX],*root; void Insert(char *s) { node *p=root; for(int i=0;s[i];i++) { int index=s[i]-'a'; if(p->next[index]==NULL) p->next[index]=new node; p=p->next[index]; } p->isword=true; p->cnt++; } void Build_AC_Automation() { int rear=1,front=0; que[0]=root; root->fail=NULL; while(rear!=front) { node *cur=que[front++]; for(int i=0;i<KIND;i++) if(cur->next[i]!=NULL) { if(cur==root) cur->next[i]->fail=root; else { node *ptr=cur->fail; while(ptr!=NULL) { if(ptr->next[i]!=NULL) { cur->next[i]->fail=ptr->next[i]; if(ptr->next[i]->isword) cur->next[i]->isword=true; break; } ptr=ptr->fail; } if(ptr==NULL) cur->next[i]->fail=root; } que[rear++]=cur->next[i]; } } } int AC_search() { int ans=0; node *ptr=root; for(int i=0;msg[i];i++) { int index=msg[i]-'a'; while(ptr->next[index]==NULL&&ptr!=root) ptr=ptr->fail; ptr=ptr->next[index]; if(ptr==NULL) ptr=root; node *temp=ptr; while(temp!=NULL&&temp->cnt!=-1) { ans+=temp->cnt; temp->cnt=-1; temp=temp->fail; } } return ans; } int main(int argc, char** argv) { int t; scanf("%d",&t); while(t--) { root=new node; int n; char s[55]; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%s",s); Insert(s); } scanf("%s",msg); Build_AC_Automation(); printf("%d/n",AC_search()); } return 0; }