您的位置:首页 > 其它

AC自动机模板

2013-09-23 19:47 316 查看
struct AhoCorasickAutomata
{
int ch[maxnode][sigma_size],last[maxnode];
int fail[maxnode],val[maxnode];
int sz;
void init()
{
memset(ch[0],0,sizeof(ch[0]));
sz=1;
}
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 c=idx(s[i]);
if(!ch[u][c])
{
memset(ch[sz],0,sizeof(ch[sz]));
val[sz]=0;
ch[u][c]=sz++;
}
u=ch[u][c];
}
val[u]=v;
}
void getfail()
{
queue<int>q;
fail[0]=0;
for(int c=0;c<sigma_size;c++)
{
int u=ch[0][c];
if(u){ fail[u]=0;q.push(u);last[u]=0;}
}
while(!q.empty())
{
int r=q.front();q.pop();
for(int c=0;c<sigma_size;c++)
{
int u=ch[r][c];
if(!u){ch[r][c]=ch[fail[r]][c];continue;}
q.push(u);
fail[u]=ch[fail[r]][c];
last[u] = val[fail[u]]?fail[u]:last[fail[u]];
}
}
}
void print(int j)
{
if(j)
{
printf("%d\n",val[j]);
print(last[j]);
}
}
void find(char *T)
{
int n=strlen(T);
int j=0;
for(int i=0;i<n;i++)
{
int c=idx(T[i]);
j=ch[j][c];
if(val[j]) print(j);
else if(last[j]) print(last[j]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: