bzoj3940[Usaco2015 Feb]Censoring AC自动机

同3942,建出AC自动机以后直接用栈来加入,只要在fail树上匹配成功就弹出。
复习一波AC自动机。。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=1e5+5;
int fail[N],top,tot,q[N],ch[N][27],dep[N];
char s1[N],s[N];
int n,a[N];
char st[N];
inline int newnode()
{
    tot++;
    fo(i,0,25)ch[tot][i]=-1;
    return tot;
}
inline void ins()
{
    int n=strlen(s1+1),x=1;
    fo(i,1,n)
    {
        if (ch[x][s1[i]-'a']==-1)ch[x][s1[i]-'a']=newnode();
        x=ch[x][s1[i]-'a'];
    }
    dep[x]=n;
}
inline void AC_mach()
{
    int t=0,w=0;
    fail[1]=1;
    fo(i,0,25)
    if (ch[1][i]==-1)ch[1][i]=1;
    else{
        fail[ch[1][i]]=1;
        q[++w]=ch[1][i];
    }
    while (t<w)
    {
        int x=q[++t];
        fo(i,0,25)
        if (ch[x][i]==-1)ch[x][i]=ch[fail[x]][i];
        else
        {
            fail[ch[x][i]]=ch[fail[x]][i];
            q[++w]=ch[x][i];
        }
    }
}
int main()
{
    scanf("%s",s+1);
    scanf("%d",&n);
    tot=0;
    newnode();
    fo(i,1,n)scanf("%s",s1+1),ins();
    AC_mach();
    int x=1,len=strlen(s+1);
    a[0]=1;
    fo(i,1,len)
    {
        st[++top]=s[i];
        x=ch[x][s[i]-'a'];
        a[top]=x;
        if (dep[x])top-=dep[x],x=a[top];
    }
    fo(i,1,top)printf("%c",st[i]);
    printf("\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值