zoukankan      html  css  js  c++  java
  • 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)<<'
    ';
    }
  • 相关阅读:
    kickstart_Round C 2020
    4.26腾讯笔试题
    [jvm][面试]JVM 调优总结
    Django中的Model(操作表)
    C++ 无锁数据结构
    masstree Seastar
    java logAspect
    vimrc
    GopherChina 2018
    RocketMQ
  • 原文地址:https://www.cnblogs.com/liulex/p/11318988.html
Copyright © 2011-2022 走看看