HDU 3065(DFA 水题)

#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxc = 2000000 + 10;
const int maxn = 50009;
struct AC{
    long long cnt[maxn];
    int f[maxn],last[maxn],val[maxn],ch[maxn][26];
    int sz;
    queue<int> que;
    void init(){
        memset(cnt,0,sizeof(cnt));
        memset(f,0,sizeof(f));
        memset(last,0,sizeof(last));
        memset(ch,0,sizeof(ch));
        memset(val,0,sizeof(val));
        sz = 0;
    }
    int idx(char c){
        return c - 'A';
    }
    void ac_insert(char* str,int v){
        int u = 0;
        for(int i = 0; str[i]; i++ ){
            int c = idx(str[i]);
            if(!ch[u][c]){
                ch[u][c] = ++sz;
            }
            u = ch[u][c];
        }
        val[u] = v;
    }
    void fail(){
        for(int i = 0; i < 26; i++){
            if(ch[0][i]){
                que.push(ch[0][i]);
            }
        }
        while(!que.empty()){
            int r = que.front(); que.pop();
            for(int i = 0; i < 26; i++){
                int u = ch[r][i];
                if(!u){ch[r][i] = ch[ f[r] ][i]; continue;}
                que.push(u);
                int v = f[r];
                while(v && !ch[v][i]) v = f[v];
                f[u] = ch[v][i];
                last[u] = val[ f[u] ] ? f[u] : last[ f[u] ];
            }
        }

    }
    void calc(int j){
        if(!j) return;
        cnt[val[j] ]++;
        calc(last[j]);
    }
    void ac_find(char* str){
        int u = 0;
        for(int i = 0; str[i]; i++){
            if(str[i] < 'A' || str[i] > 'Z'){u = 0; continue;}
            int c = idx(str[i]);
            u = ch[u][c];
            if(val[u]){
                calc(u);
            }
            else {
                calc(last[u]);
            }
        }
    }
};
AC ac;
int main(){
    int N;
    //freopen("123.txt","r",stdin);
    char str[maxc];
    char str2[1010][55];

    while(~scanf("%d",&N)){
             ac.init();
    for(int i = 1; i <= N; i++){
        scanf("%s",str2[i]);
        ac.ac_insert(str2[i],i);
    }
    ac.fail();
    scanf("%s",str);

    ac.ac_find(str);
    for(int i = 1; i <= N; i++){
        if(!ac.cnt[i]) continue;
        printf("%s: %d\n",str2[i],ac.cnt[i]);
    }
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/ehdhg13455/article/details/82355105