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

被折叠的 条评论
为什么被折叠?



