【模板】AC自动机

模板题

 

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
struct mzls
{
	int next[26],fail,count;
	void init()
	{
		memset(next,-1,sizeof(next));
		count=0;
		fail=0;
	}
}s[500005];
char s1[55],s2[1000005];
int n,len,id;
inline void ins()
{
	int nt=0;
	for(int i=0;i<len;i++)
	{
		int j=s1[i]-'a';
		if(s[nt].next[j]==-1)
		{
			s[++id].init();
			s[nt].next[j]=id;
		}
		nt=s[nt].next[j];
	}
	s[nt].count++;
}
inline void make_fail()
{
	queue<int>que;
	for(int i=0;i<26;i++)
		if(s[0].next[i]!=-1)
			que.push(s[0].next[i]);
	int nt;
	while(!que.empty())
	{
		int ml=que.front();
		que.pop();
		for(int i=0;i<26;i++)
			if(s[ml].next[i]!=-1)
			{
				int to=s[ml].next[i];
				que.push(to);
				nt=s[ml].fail;
				while(nt>0&&s[nt].next[i]==-1)
					nt=s[nt].fail;
				if(s[nt].next[i]!=-1)
					nt=s[nt].next[i];
				s[to].fail=nt;
			}
	}
}
inline int cal()
{
	int ans=0,nt=0;
	for(int i=0;i<len;i++)
	{
		int j=s2[i]-'a';
		while(nt>0&&s[nt].next[j]==-1)
			nt=s[nt].fail;
		if(s[nt].next[j]!=-1)
		{
			nt=s[nt].next[j];
			int ml=nt;
			while(ml&&s[ml].count!=-1)
			{
				ans+=s[ml].count;
				s[ml].count=-1;
				ml=s[ml].fail;
			}
		}
	}
	return ans;
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		s[id=0].init();
		while(n--)
		{
			scanf("%s",s1);
			len=strlen(s1);
			ins();
		}
		make_fail();
		scanf("%s",s2);
		len=strlen(s2);
		printf("%d\n",cal());
	}
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值