AC自动机

AC自动机:简单版
询问每个字符串是否出现过
为了压缩时间,我们当碰到一个ed结点的时候,
如果该结点没有访问过,我们就按照fail跳一遍
如果该结点之前统计过,我们就不用顺着fail指针再统计了

//这里写代码片
#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

const int N=1000005;
int n,ch[N][26],tot=0,word[N];
char s[N],w[N]; 
bool ed[N];
int Q[N],tou,wei,cnt[N],fail[N];

void build(int bh)
{
    int len=strlen(w);
    int now=0;
    for (int i=0;i<len;i++)
    {
        int x=w[i]-'a';
        if (!ch[now][x]) ch[now][x]=++tot;
        now=ch[now][x];
    }
    ed[now]=1;
    word[bh]=now;
}

void makefail()
{
    tou=wei=0;
    for (int i=0;i<26;i++)
        if (ch[0][i])
            Q[++wei]=ch[0][i];
    while (tou<wei)
    {
        int now=Q[++tou];
        for (int i=0;i<26;i++)
        {
            if (!ch[now][i])
            {
                ch[now][i]=ch[fail[now]][i];
                continue;
            }
            Q[++wei]=ch[now][i];
            fail[ch[now][i]]=ch[fail[now]][i];
        }
    }
}

void solve()
{
    memset(cnt,0,sizeof(cnt));
    int len=strlen(s);
    int now=0,ans=0;
    for (int i=0;i<len;i++)
    {
        int x=s[i]-'a';
        while (now&&!ch[now][x]) now=fail[now];
        now=ch[now][x];
        if (ed[now]&&cnt[now]==0)         //cnt=0 第一次访问 
        {
            cnt[now]++; 
            int f=now;
            while (f&&cnt[f]==0)
            {
                f=fail[f]; 
                cnt[f]++;
            }
        }
    }

    for (int i=1;i<=n;i++) if (cnt[word[i]]) ans++;
    printf("%d",ans);
}

int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    {
        scanf("%s",w);
        build(i);
    }
    makefail();
    scanf("%s",s);
    solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值