您的位置:首页 > 其它

HDU2222 AC自动机水题

2016-02-09 15:57 393 查看
#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;

const int dmax=100100;
struct node{
int count,flag;
struct node *next[26],*fail,*fa;
node(){
count=flag=0;
fail=fa=NULL;
memset(next,0,sizeof(next));
}
};
struct node *root,*h,*tmp,*fa;
struct node *q[60*10100];
char p[10100][60];
char s[1000100];
int ans;

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;
}
h=h->next[k];
}
h->count++;
}
void create_fail(){
int i,f=0,l=1;
q[1]=root;
while (f<l){
h=q[++f];
For(i,0,25)
if (h->next[i]!=NULL){
tmp=h->fail;
while (tmp!=NULL && tmp->next[i]==NULL) tmp=tmp->fail;
h->next[i]->fail=tmp==NULL?root:tmp->next[i];
q[++l]=h->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;
while (h!=NULL && h->next[k]==NULL) h=h->fail;
h=h==NULL?root:h->next[k];
tmp=h;
while (tmp!=root){
if (!tmp->flag && tmp->count){
ans+=tmp->count;
tmp->flag=1;
}
tmp=tmp->fail;
}
}
}
void dfs(struct node *f){
int i;
For(i,0,25)
if (f->next[i]!=NULL)
dfs(f->next[i]);
delete f;
}

int main(){
int i,j,k,m,n,T;
scanf("%d",&T);
while (T--){
root=new node;
root->fail=NULL;
ans=0;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: