Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 22721 Accepted Submission(s): 7553
#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int N=26; struct Trie{ Trie *fail; //失败指针 Trie *next[N]; //Tire每个节点的26个子节点(最多26个字母) int count; //是否为该单词的最后一个节点 Trie(){ //构造函数初始化 fail=NULL; count=0; memset(next,NULL,sizeof(next)); } }*q[500010]; //队列,方便用于bfs构造失败指针 char word[55]; //输入的单词 char str[1000010]; //模式串 int head,tail; //队列的头尾指针 void Insert(char *str,Trie *Root){ Trie *loc=Root; int i=0; while(str[i]!='\0'){ int id=str[i]-'a'; if(loc->next[id]==NULL) loc->next[id]=new Trie(); loc=loc->next[id]; i++; } loc->count++; } void AC_automation(Trie *Root){ Root->fail=NULL; q[head++]=Root; Trie *cur,*tmp; while(head!=tail){ cur=q[tail++]; tmp=NULL; for(int i=0;i<26;i++){ if(cur->next[i]!=NULL){ if(cur==Root) cur->next[i]->fail=Root; else{ tmp=cur->fail; while(tmp!=NULL){ if(tmp->next[i]!=NULL){ cur->next[i]->fail=tmp->next[i]; break; } tmp=tmp->fail; } if(tmp==NULL) cur->next[i]->fail=Root; } q[head++]=cur->next[i]; } } } } int query(Trie *Root){ int i=0,cnt=0; Trie *loc=Root,*tmp; while(str[i]!='\0'){ int id=str[i]-'a'; while(loc->next[id]==NULL && loc!=Root) loc=loc->fail; loc=loc->next[id]; loc=(loc==NULL)?Root:loc; tmp=loc; while(tmp!=Root && tmp->count!=-1){ cnt+=tmp->count; tmp->count=-1; tmp=tmp->fail; } i++; } return cnt; } int main(){ //freopen("input.txt","r",stdin); int t,n; scanf("%d",&t); while(t--){ head=tail=0; Trie *Root=new Trie(); scanf("%d",&n); getchar(); while(n--){ gets(word); Insert(word,Root); } AC_automation(Root); scanf("%s",str); printf("%d\n",query(Root)); } return 0; }