#include <iostream> #include <cstdio> #include <cstring> #include <stack> using namespace std; struct tree { int count; tree *next[26]; tree *fail; }; stack < tree* > Q;//此处错误,应该是队列而非栈,未修改 char keyword[55]; char str[1111111]; tree *root; void insert(tree *root,char *word) { int i,j,k,l,m,n; int index; tree *p=root,*newnode; l=strlen(word); for(i=0; i<l; i++) { index=word[i]-'a'; if(!p->next[index]) { newnode=new tree; for(j=0; j<26; j++) { newnode->next[j]=NULL; } newnode->count=0; newnode->fail=NULL; p->next[index]=newnode; } p=p->next[index]; } p->count++; } void failed(tree *root) { int i,j,k,l,m,n; while(!Q.empty()) { Q.pop(); } Q.push(root); tree *temp,*p; while(!Q.empty()) { temp=Q.top(); Q.pop(); for(i=0; i<26; i++) { if(temp->next[i]) { if(temp==root) temp->next[i]->fail=root; else { p=temp->fail; while(p) { if(p->next[i]) { temp->next[i]->fail=p->next[i]; break; } p=p->fail; } if(p==NULL) temp->next[i]->fail=root; } Q.push(temp->next[i]); } } } } int query(tree *root) { int i,j,k,l,m,n; int cnt=0; int index; tree *p=root; l=strlen(str); for(i=0; i<l; i++) { index=str[i]-'a'; while(!p->next[index]&&p!=root) p=p->fail; p=p->next[index]; if(!p) p=root; tree *temp=p; while(temp!=root) { if(temp->count>=0) { cnt+=temp->count; temp->count=-1; } else break; temp=temp->fail; } } return cnt; } int del(tree *T) { int i; if(T==NULL) return 0; for(i=0;i<26;i++) { if(T->next[i]!=NULL) del(T->next[i]); } delete T; return 0; } int main() { int i,j,k,l,m,n; int t; cin>>t; while(t--) { root=new tree; for(i=0; i<26; i++) { root->next[i]=NULL; } root->fail=NULL; root->count=0; cin>>n; for(i=0; i<n; i++) { cin>>keyword; insert( root , keyword ); } failed(root); cin>>str; k=query(root); del(root); cout<<k<<endl; } }
hdu 2222
最新推荐文章于 2020-09-14 18:22:41 发布