ac自动机。参考:http://www.cppblog.com/mythit/archive/2009/04/21/80633.html
#include<iostream> #include<cstdio> #include<string> #include<queue> using namespace std; class node { public: node *fail; node *next[28]; int count; node() { count=0; memset(next,NULL,sizeof(next)); } }; node *tire,*que[500009]; char str[1000009]; void insert(char ch[]) { int i,len=strlen(ch); node *p=tire; for(i=0;i<len;i++) { int k=ch[i]-'a'; if(p->next [k]==NULL) p->next [k]=new node(); p=p->next [k]; } p->count ++; } void bfs() { int front=0,rear=0,i; rear++; tire->fail=NULL; que[rear]=tire; while(front!=rear) { front++; node *temp=que[front],*p; for(i=0;i<26;i++) if(temp->next[i]!=NULL) { p=temp->fail ; while(p!=NULL) { if(p->next [i]!=NULL) { temp->next [i]->fail =p->next [i]; break; } p=p->fail ; } if(p==NULL) temp->next [i]->fail =tire; rear++; que[rear]=temp->next [i]; } } } void solve() { int cnt=0,i,len=strlen(str); node * temp=tire; for(i=0;i<len;i++) { int k=str[i]-'a'; while(temp->next [k]==NULL&&temp!=tire) temp=temp->fail ; temp=temp->next [k]; if(temp==NULL) temp=tire; node *p=temp; while(p !=tire&&p->count !=-1) { cnt+=p->count ; p->count =-1; p=p->fail ; } } cout<<cnt<<endl; } int main() { int test,i,n; char ch[65]; scanf("%d",&test); while(test--) { scanf("%d",&n); getchar(); tire= new node(); while(n--) { scanf("%s",ch); insert(ch); } bfs(); scanf("%s",str); solve(); } return 0; }