[HDU2896]病毒侵袭(AC自动机)

本文介绍了一道关于AC自动机的编程题目,并提供了完整的代码实现。通过对代码的详细解析,帮助读者理解AC自动机的工作原理及其在字符串匹配中的应用。

题目:

我是超链接

题解:

AC自动机模板题

代码:

#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
char st[10005];
int tot=0,ch[100005][130],is_end[100005],fail[100005],ans[1005];
bool vis[100005];
void trie(int id)
{
	int i;
	scanf("%s",st);
	int l=strlen(st),now=0;
	for (i=0;i<l;i++)
	{
		int x=st[i];
		if (!ch[now][x]) ch[now][x]=++tot;
		now=ch[now][x];
	}
	is_end[now]=id;
}
void sp()
{
	int i;
	queue <int> q;
	for (i=0;i<=128;i++)
	  if (ch[0][i]) q.push(ch[0][i]);
	while (!q.empty())
	{
		int now=q.front();q.pop();
		for (i=0;i<=128;i++)
		{
			if (!ch[now][i])
			{
				ch[now][i]=ch[fail[now]][i];
				continue;
			}
			fail[ch[now][i]]=ch[fail[now]][i];
			q.push(ch[now][i]);
		}
	}
}
void ac()
{
	int i;
	scanf("%s",st);
	int l=strlen(st),now=0;
    for (i=0;i<l;i++)
    {
    	vis[now]=1;
    	int x=st[i];
    	int y=ch[now][x];
    	while (y && !vis[y])
    	{
    		vis[y]=1;
    		if (is_end[y]) ans[++ans[0]]=is_end[y];
    		y=fail[y];
		}
		now=ch[now][x];
	}
}
int main()
{
	int n,i,j,m;
	scanf("%d",&n);
	for (i=1;i<=n;i++)
	  trie(i);
	sp();
	scanf("%d",&m);
	int tot=0;
	for (i=1;i<=m;i++)
	{
		memset(ans,0,sizeof(ans));
		memset(vis,0,sizeof(vis));
		ac();
		if (ans[0])	
		{
			printf("web %d:",i);
			sort(ans+1,ans+ans[0]+1);
		    for (j=1;j<=ans[0];j++)
		      printf(" %d",ans[j]);
		    printf("\n");
		    tot++;
		}
	}
	printf("total: %d",tot);
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值