HDU-2222 Keywords Search(AC自动机模板题)

/*
* @Author: windystreet
* @Date:   2018-07-26 09:22:19
* @Last Modified by:   windystreet
* @Last Modified time: 2018-07-26 14:01:48
*/
#include<bits/stdc++.h>

using namespace std;

#define X first
#define Y second
#define eps  1e-2
#define gcd __gcd
#define pb push_back
#define PI acos(-1.0)
#define lowbit(x) (x)&(-x)
#define bug printf("!!!!!
");
#define mem(x,y) memset(x,y,sizeof(x))

typedef long long LL;
typedef long double LD;
typedef pair<int,int> pii;
typedef unsigned long long uLL;

const int maxn = 1e6+7;
const LL  INF  = 1<<30;
const int mod  = 1e9+7;

int ch[maxn][26];
int val[maxn],last[maxn],sz;
int f[maxn];
char s[maxn];
int idx(char a){return a - 'a';}
void init(){
    sz = 1;
    mem(ch[0],0);
    mem(last,0);
}
void insert(){
    int len = strlen(s),cur = 0;
    for(int i = 0; i < len; i++){
        int c = idx(s[i]);
        if(!ch[cur][c]){
            mem(ch[sz],0);
            val[sz] = 0;
            ch[cur][c] = sz++;
        }
        cur = ch[cur][c];
    }
    val[cur]++;

}
void getfail(){
    queue<int>q;
    f[0] = 0;
    int u ;
    for(int i=0;i<26;i++){
        u = ch[0][i];
        if(u){
            f[u] = 0;
            q.push(u);
            last[u] = 0;
        }
    }
    while(!q.empty()){
        int cur = q.front();q.pop();
        for(int i=0;i<26;i++){
            u = ch[cur][i];
            if(!u){ch[cur][i] = ch[f[cur]][i]; continue;}
            q.push(u);
        
        int tmp = f[cur];
        if(tmp && !ch[tmp][i]) tmp = ch[f[tmp]][i];
        f[u] = ch[tmp][i];
        last[u] = val[f[u]] ? f[u] : last[f[u]];
        }

    }
}
int find(){
    int cnt = 0;
    int len = strlen(s), u = 0;
    for(int i=0;i<len;i++){
        int c = idx(s[i]);
        u = ch[u][c];
        for(int tmp = u ;tmp>0&&val[tmp]>0;tmp = f[tmp]){
            cnt += val[tmp],val[tmp] = 0;
        }
    }
    return cnt;
}

void solve(){
    int n;
    scanf("%d",&n);
    init();
    for (int i = 0; i < n; ++i)
    {
        scanf("%s",s);
        insert();
        /* code */
    }
    getfail();
    scanf("%s",s);
    printf("%d
",find());
    return;
}

int main()
{
//    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
//    ios::sync_with_stdio(false);
    int t = 1;
    scanf("%d",&t);
    while(t--){
    //    printf("Case %d: ",cas++);
        solve();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/windystreet/p/9376550.html