您的位置:首页 > 其它

AC自动机模板

2016-08-03 11:38 246 查看
AC自动机主要是用于多模式串的匹配问题,按照我的理解,AC自动机就是在Tire树上实现KMP算法,由于AC自动机加入了失败指针,所以可以把他看成一个状态转移的图。

给出模板

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxnode=240005;
const int maxn=1010;
const int kind=26;
const int inf=0x7f7f7f7f;
struct node
{
int ch[maxnode][kind],sz;
int val[maxnode],fail[maxnode],last[maxnode];
int dp[maxn][maxnode];
void init()
{
sz=1;
memset(ch[0],0,sizeof(ch[0]));
memset(dp,inf,sizeof(dp));
}
int idx(char c)
{
return c-'a';
}
void insert(char *s,int v)
{
int u=0,n=strlen(s);
for(int i=0;i<n;i++)
{
int id=idx(s[i]);
if(!ch[u][id])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz]=0;
ch[u][id]=sz++;
}
u=ch[u][id];
}
val[u]=v;
}
void getFail()
{
queue<int>q;
fail[0]=0;
for(int i=0;i<kind;i++)
{
int u=ch[0][i];
if(u)
{
fail[u]=0;
q.push(u);
last[u]=0;
}
}
while(!q.empty())
{
int r=q.front();
q.pop();
for(int i=0;i<kind;i++)
{
int u=ch[r][i];
if(!u)
{
ch[r][i]=ch[fail[r]][i];
continue;
}
q.push(u);
int v=fail[r];
while(v&&!ch[v][i]) v=fail[v];
fail[u]=ch[v][i];
last[u]=val[fail[u]]?fail[u]:last[fail[u]];
}
}
}
void print(int x)
{
if(x)
{
printf("%d: %d\n",x,val[x]);
print(last[x]);
}
}
void find(char *s)
{
int j=0,n=strlen(s);
for(int i=0;i<n;i++)
{
int id=idx(s[i]);
while(j&&!ch[j][id]) j=fail[j];
j=ch[j][id];
if(val[j]) print(j);
else if(last[j]) print(last[j]);
}
}
};
node ac;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: