[模板] 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\n",query(s));
    }
}
posted @ 2018-06-25 20:48  GhostCai  阅读(117)  评论(1编辑  收藏  举报