[HDU2222]Keywords Search(AC自动机)

本文介绍了一种基于AC自动机的字符串匹配算法实现模板。该模板通过构建 Trie 树并进行预处理,实现了高效的字符串匹配过程。文章详细展示了AC自动机的构建方法,包括节点的构造、失败指针的设置及匹配过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

点击打开链接

AC自动机模板

#include <cstdio>
#include <queue>
#include <cstring>
#define N 10000*50+10
using namespace std;
char st[N],ss[1000005];
int tot=0,ch[N][30],fail[N],is_end[N];
bool visit[N];
void trie()
{
	int now=0,l=strlen(st);
	for (int i=0;i<l;i++)
	  {
	  	int x=st[i]-'a';
	  	if (!ch[now][x]) ch[now][x]=++tot;
	  	now=ch[now][x];
	  }
	is_end[now]++;
}
void sp()
{
	int i;
	queue <int> q;
	for (i=0;i<26;i++)
	  if (ch[0][i]) q.push(ch[0][i]);
	while (!q.empty())
	{
		int now=q.front(); q.pop();
		for (i=0;i<26;i++)
		{
			if (!ch[now][i])
			{
				ch[now][i]=ch[fail[now]][i];
				continue;
			}
			int tmp=ch[now][i];
			fail[tmp]=ch[fail[now]][i];
			q.push(tmp);
		}
	}
}
void ac()
{
	int i;
	int l=strlen(ss),now=0,ans=0;
	for (i=0;i<l;i++)
	{
		visit[now]=1;
		int x=ss[i]-'a';
		int y=ch[now][x];
		while (y && !visit[y]) 
		{
			visit[y]=true;
			ans+=is_end[y];
			y=fail[y];
		}
		now=ch[now][x];
	}
    printf("%d\n",ans); 
}
int main()
{
	int i,t,n;
	scanf("%d",&t);
	while (t--)
	{
		tot=0;
		memset(ch,0,sizeof(ch));
		memset(visit,0,sizeof(visit));
		memset(is_end,0,sizeof(is_end));
        memset(fail,0,sizeof(fail));
		scanf("%d",&n);
	    for (i=1;i<=n;i++)
	    {
	    	scanf("%s",&st);
	    	trie();
		}
	    sp();
		scanf("%s",&ss);
		ac();  
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值