其他分享
首页 > 其他分享> > kuangbin专题十七:AC自动机

kuangbin专题十七:AC自动机

作者:互联网

HDU2222 Keywords Search

思路:AC自动机模板。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 1e6+5;
int tr[maxn][26], tot;
int e[maxn], fail[maxn];
char s[maxn];

void insert(char *s){
    int u = 0;
    for(int i = 1; s[i]; i++){
        if(!tr[u][s[i]-'a']) tr[u][s[i]-'a'] = ++tot;
        u = tr[u][s[i]-'a'];
    }
    e[u]++;
}

queue<int> q;
void build(){
    for(int i = 0; i < 26; i++)
        if(tr[0][i]) q.push(tr[0][i]);
    while(q.size()){
        int u = q.front(); q.pop();
        for(int i = 0; i < 26; i++)
            if(tr[u][i])
                fail[tr[u][i]] = tr[fail[u]][i], q.push(tr[u][i]);
            else
                tr[u][i] = tr[fail[u]][i];
    }
}

int query(char *t){
    int u = 0, res = 0;
    for(int i = 1; t[i]; i++){
        u = tr[u][t[i]-'a'];
        for(int j = u; j && e[j]!=-1; j = fail[j])
            res += e[j], e[j] = -1;
    }
    return res;
}

void init(){
    tot = 0;
    memset(tr, 0, sizeof(tr));
    memset(fail, 0, sizeof(fail));
    memset(e, 0, sizeof(e));
}

int main(){
    int T;
    scanf("%d", &T);
    while(T--){
        int n;
        init();
        scanf("%d", &n);
        for(int i = 0; i < n; i++) scanf("%s", s+1), insert(s);
        scanf("%s", s+1);
        build();
        printf("%d\n", query(s));
    }
    return 0;
}
View Code

 

标签:AC,include,int,tr,++,maxn,kuangbin,fail,自动机
来源: https://www.cnblogs.com/arch/p/14769898.html