zoukankan      html  css  js  c++  java
  • [模板] AC自动机

    HDU2222

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<queue>
    #define C(x) ((x)-('a'))
    using namespace std;
    
    const int MAXN=500005;
    
    int ch[MAXN][26],fail[MAXN],ed[MAXN];
    int root,tot;
    inline int newnode() {
        ed[++tot]=0;                            //多组数据 
        for(int i=0;i<26;i++) ch[tot][i]=0;     //一定记得清空 
        return tot;
    }
    void insert(char *s) {
        int lens=strlen(s),cur=root;
        for(int i=0; i<lens; i++) {
            if(!ch[cur][C(s[i])]) ch[cur][C(s[i])]=newnode();
            cur=ch[cur][C(s[i])];
        }
        ed[cur]++;
    }
    queue<int> Q;
    void build() {
        fail[root]=root;
        for(int i=0; i<26; i++) {
            if(!ch[root][i]) ch[root][i]=root;
            else {
                fail[ch[root][i]]=root;
                Q.push(ch[root][i]);
            }
        }
        while(!Q.empty()) {
            int top=Q.front();
            Q.pop();
            for(int i=0; i<26; i++) {
                if(!ch[top][i]) ch[top][i]=ch[fail[top]][i];
                else {
                    fail[ch[top][i]]=ch[fail[top]][i];
                    Q.push(ch[top][i]);
                }
            }
        }
    }
    int query(char *s) {
        int lens=strlen(s),cur=root,ret=0;
        for(int i=0; i<lens; i++) {
            cur=ch[cur][C(s[i])];
            int tmp=cur;
            while(tmp!=root) {
                ret+=ed[tmp];
                ed[tmp]=0;
                tmp=fail[tmp];
            }
        }
        return ret;
    }
    char s[1000001];
    int T,n;
    int main() {
        scanf("%d",&T);
        while(T--) {
            scanf("%d",&n);
            tot=0;
            root=newnode();
            for(int i=1; i<=n; i++) {
                scanf("%s",s);
                insert(s);
            }
            build();
            scanf("%s",s);
            printf("%d
    ",query(s));
        }
    }

    本文来自博客园,作者:GhostCai,转载请注明原文链接:https://www.cnblogs.com/ghostcai/p/9247375.html

  • 相关阅读:
    mysql_Navicat数据库破解
    SpringBoot+ Mybatis 搭建
    SSH框架搭建
    SSM 框架搭建
    android 网络_网络图片查看器
    android 网络_网络源码查看器
    android ListView_显示数据库数据
    android ListView_新闻案例
    android ListView的怪异现象
    android ListView_Tiger
  • 原文地址:https://www.cnblogs.com/ghostcai/p/9247375.html
Copyright © 2011-2022 走看看