AC自动机

AC自动机模板

#include<bits/stdc++.h>
using namespace std;
#define maxn 1000005
#define maxm 28
struct AC{
int trieN;
int ch[maxn][maxm];
int val[maxn];
int fail[maxn];
void init()
{
    trieN=-1;
    newnod();
}
int newnod()
{
    memset(ch[++trieN],0,sizeof ch[0]);
    val[trieN]=fail[trieN]=0;
    return trieN;
}
void insert(const string & str)
{
    int cur=0;
    for(int i=0;i<str.size();i++){
        int d=str[i]-'a';
        if(!ch[cur][d]){
            ch[cur][d]=newnod();
        }
        cur=ch[cur][d];
    }
    val[cur]++;
}
void build()
{
    queue<int> q;
    for(int i=0;i<maxm;i++){
        if(ch[0][i]){
            q.push(ch[0][i]);
        }
    }
    while(!q.empty()){
        int cur=q.front();
        q.pop();
        for(int i=0;i<maxm;i++){
            if(ch[cur][i]){
                fail[ch[cur][i]]=ch[fail[cur]][i];
                q.push(ch[cur][i]);
            }else{
                ch[cur][i]=ch[fail[cur]][i];
            }
        }
    }
}

int query(const string & str)
{

    int res=0,cur=0;
    for(int i=0;str[i];i++){
        int d=str[i]-'a';
        cur=ch[cur][d];
        int tmp=cur;
        while(tmp&&val[tmp]>=0){
            res+=val[tmp];
            val[tmp]=-1;
            tmp=fail[tmp];
        }
    }
    return res;
}
}ac;

int main()
{
    string s;
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        cin>>s;
        ac.insert(s);
    }
    ac.build();
    cin>>s;
    cout<<ac.query(s)<<'\n';
}

 

posted @ 2019-08-08 08:33  liulex  阅读(109)  评论(0编辑  收藏  举报