#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define For(i,j,k) for (i=j;i<=k;i++)
using namespace std;
struct node{
int count,flag;
bool r;
struct node *next[26],*fa,*fail;
node(){
count=flag=r=0;
fail=fa=NULL;
memset(next,0,sizeof(next));
}
};
struct node *root,*h,*fa,*tmp,*temp;
struct node *q[606000];
char p[10100][110];
char s[1000100];
int ans,len=0;
void insert(char *w){
int i,k,n=strlen(w);
h=root;
For(i,0,n-1){
k=w[i]-97;
if (h->next[k]==NULL){
tmp=new node;
tmp->fa=h;
h->next[k]=tmp;
tmp->r=1;
}
h=h->next[k];
}
h->count++;
h->flag=0;
}
void create_fail(){
int i,f=0,l=1;
q[1]=root;
while (f<l){
fa=q[++f];
For(i,0,25)
if (fa->next[i]==NULL){
fa->next[i]=fa==root?root:fa->fail->next[i];
fa->next[i]->r=0;
}else{
fa->next[i]->fail=fa==root?root:fa->fail->next[i];
q[++l]=fa->next[i];
}
}
}
void auto_search(char *s){
int i,j,k,m,n=strlen(s);
h=root;
For(i,0,n-1){
k=s[i]-97;
h=h->next[k];
tmp=h;
while (tmp!=NULL){
if (tmp->count && !tmp->flag){
ans+=tmp->count;
tmp->flag=1;
}
tmp=tmp->fail;
}
}
}
void dfs(struct node *t){
int i;
if (!t->r){
delete t;
return;
}
For(i,0,25)
if (t->next[i]!=NULL)
dfs(t->next[i]);
delete t;
}
int main(){
int i,j,k,m,n=0,T;
scanf("%d",&T);
while (T--){
ans=0;
memset(p,0,sizeof(p));
memset(s,0,sizeof(s));
root=new node;
root->fail=NULL;
root->r=1;
scanf("%d",&n);
getchar();
For(i,1,n){
gets(p[i]);
insert(p[i]);
}
gets(s);
create_fail();
auto_search(s);
printf("%d\n",ans);
dfs(root);
}
return 0;
}
HDU2222 AC自动机水题 (Trie图优化)
最新推荐文章于 2021-08-17 21:06:48 发布