UVALive-4670 AC自动机入门题 求出现次数最多的子串

/**
链接:http://vjudge.net/problem/UVALive-4670
详见lrj训练指南P216
*/
#include<bits/stdc++.h>
using namespace std;
#define P pair<int,int>
#define ms(x,y) memset(x,y,sizeof x)
#define LL long long
const int maxn = 22;
const int mod = 1e9+7;
const int maxnode = 71*150;
const int sigma_size = 26;
map<string,int> mp;
int cnt[155];
struct AhoCorasickAutomata
{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int sz;
    int f[maxnode];
    int last[maxnode];
    void clear(){sz = 1; memset(ch[0],0,sizeof ch[0]); }
    int idx(char c){return c-'a'; }

    void insert(char *s,int v)
    {
        int u = 0, n = strlen(s);
        for(int i = 0; i < n; i++){
            int c = idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz], 0, sizeof ch[sz]);
                val[sz] = 0;
                ch[u][c] = sz++;
            }
            u = ch[u][c];
        }
        val[u] = v;
    }

    void find(char *T){
        int n = strlen(T);
        int j = 0;
        for(int i = 0; i < n; i++){
            int c = idx(T[i]);
            //while(j&&!ch[j][c]) j = f[j];
            j = ch[j][c];
            if(val[j]) print(j);
            else if(last[j]) print(last[j]);
        }
    }

    void print(int j)
    {
        if(j){
            cnt[val[j]]++;
            print(last[j]);
        }
    }

    void getFail(){
        queue<int> q;
        f[0] = 0;
        for(int c = 0; c < sigma_size; c++){
            int u = ch[0][c];
            if(u){f[u] = 0; q.push(u); last[u] = 0;}
        }

        while(!q.empty()){
            int r = q.front(); q.pop();
            for(int c = 0; c < sigma_size; c++){
                int u = ch[r][c];
                if(!u){
                    ch[r][c] = ch[f[r]][c]; continue;
                }//if(!u) continue;
                q.push(u);
                int v = f[r];
                while(v&&!ch[v][c]) v = f[v];
                f[u] = ch[v][c];
                last[u] = val[f[u]] ? f[u] : last[f[u]];
            }
        }
    }

} ac ;
char a[155][77];
char s[1000006];
int main()
{
    int n;
    while(scanf("%d",&n)==1&&n)
    {
        ac.clear();
        mp.clear();
        memset(cnt, 0, sizeof cnt);
        for(int i = 1; i <= n; i++){
            scanf("%s",a[i]);
            ac.insert(a[i],i);
            mp[string(a[i])] = i;
        }
        scanf("%s",s);
        ac.getFail();
        ac.find(s);
        int mas = 0;
        for(int i = 1; i <= n; i++){
            if(cnt[i]>mas){mas = cnt[i];}
        }
        printf("%d
",mas);
        for(int i = 1; i <= n; i++){
            if(cnt[mp[string(a[i])]]==mas){
                printf("%s
",a[i]);
            }
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xiaochaoqun/p/7507169.html