HDU2222 AC自动机水题

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值