hdu2222(ac自动机模板)

本文提供了一个AC自动机的实战代码实现,并通过一个具体的例子展示了如何构建AC自动机及其实现模式匹配的过程。代码中详细说明了节点结构、添加字符串、预处理以及求解等关键步骤。
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=50*10000+10;
struct node{
    int son[26],f,v,cnt;
    void rnw(){memset(son,0,sizeof(son));f=v=cnt=0;}
}ch[maxn];
char s[100],t[1000010];
int tot,q[maxn],head,tail,T,n;
void add(char s[]){
    int u=0,len;
    len=strlen(s);
    for(int i=0;i<len;++i){
        int c=s[i]-'a';
        if(!ch[u].son[c]){ch[u].son[c]=++tot;}
        u=ch[u].son[c];
    }
    ch[u].cnt++;
}
void pre(){
    head=tail=0;
    ch[0].f=0;
    for(int i=0;i<26;++i){
        int u=ch[0].son[i];
        if(u){
            ch[u].f=0;
            q[++tail]=u;
        }
    }
    while(head<tail){
        int now=q[++head];
        for(int i=0;i<26;++i){
            int u=ch[now].son[i];
            if(!u){
                ch[now].son[i]=ch[ch[now].f].son[i];
                continue;
            }
            q[++tail]=u;
            int v=ch[now].f;
            while(v&&!ch[v].son[i])v=ch[v].f;
            ch[u].f=ch[v].son[i];
        }
    }
}
ll solve(char t[]){
    ll res=0;
    int len,u=0;
    len=strlen(t);
    for(int i=0;i<len;++i){
        int c=t[i]-'a';
        u=ch[u].son[c];
        //if(ch[u].cnt){
            int tmp=u;
            while(tmp){
                if(ch[tmp].cnt>=0){
                    res+=ch[tmp].cnt;
                    ch[tmp].cnt=-1;
                }
                else{break;}
                tmp=ch[tmp].f;
            }
        //}
    }
    return res;
}
int main(){
    cin>>T;
    while(T--){
        tot=0;
        for(int i=0;i<=500000;++i)ch[i].rnw();
        scanf("%d",&n);
        for(int i=1;i<=n;++i){
            scanf("%s",s);add(s);
        }
        scanf("%s",t);
        pre();
        printf("%lld\n",solve(t));
    }
    system("pause");
    return 0;
}
/*
1
2
abcdefgh
efg
abcdefgh
*/

PS:那个注释掉的if不能加,这个串就算不是一个结尾也要往前跳,hack数据就写在下面。

转载于:https://www.cnblogs.com/dibaotianxing/p/7967053.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值