aho-corasick 自动机模板(来源于刘汝佳老师的白书)

/*以杭电的2222题为例,代码如下*/

 

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

#define N 241000

int ch[N][26],cnt,f[N],last[N],val[N];
struct aho_corasick
{
    aho_corasick(){
        cnt=0;
        memset(ch,0,sizeof(ch));
        memset(val,0,sizeof(val));
    }
    int newnode(){ return ++cnt; }
    int idx(char c){ return c-'a'; }
    void insert(char *s,int n)
    {
        int root=0,i;
        for(i=0;i<n;i++)
        {
            int u=idx(s[i]);
            if(!ch[root][u])ch[root][u]=newnode();
            if(i==n-1) val[ch[root][u]]++;
            root=ch[root][u];
        }
    }
    void getfail()
    {
            queue <int> q;
            f[0]=0;
            int i,u;
            for(i=0;i<26;i++)
            {
                u=ch[0][i];
                if(u){ f[u]=0; q.push(u);last[u]=0; }
            }
            while(!q.empty())
            {
                int r=q.front(); q.pop();
                for(i=0;i<26;i++)
                {
                    u=ch[r][i];
                    if(!u){ ch[r][i]=ch[f[r]][i]; continue; }
                    q.push(u);
                    f[u]=ch[f[r]][i];
                    last[u]=val[f[u]]?f[u]:last[f[u]];
                }
            }
    }
    int find(char *t,int n)
    {
        int i,j=0,ans=0,temp;
        for(i=0;i<n;i++)
        {
            int c=idx(t[i]);
            j=ch[j][c];
            temp=j;
            while(temp&&val[temp]!=-1)
            {
                ans+=val[temp];
                val[temp]=-1;
                temp=last[temp];
            }
        }
        return ans;
    }
};
char str[1100000];
int main()
{
    
    int cas,i,n;
    scanf("%d",&cas);
    while(cas--)
    {
        scanf("%d",&n);
        aho_corasick ac;
        for(i=1;i<=n;i++)
        {
            scanf("%s",str);
            ac.insert(str,strlen(str));
        }
        ac.getfail();
        scanf("%s",str);
        printf("%d\n",ac.find(str,strlen(str)));
    }
    return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值