hdu2222AC自动机

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <string.h>
#include <map>
#include <vector>

const int nodeSize = 500000 ;
const int alphaSize = 26 ;
struct AC{
    int next[nodeSize][alphaSize] ;
    int cnt[nodeSize] ;
    int fail[nodeSize] ;
    int totel ;
    int root ;

    void clear(){
         totel = 0 ;
         root = newNode() ;
    }

    int newNode(){
        cnt[totel] = 0 ;
        memset(next[totel] , 0 , sizeof(next[totel])) ;
        return totel++ ;
    }

    void add(char *s){
         int now = root ;
         for(int i = 0 ; s[i] ; i++){
              int son = s[i] - 'a' ;
              if(! next[now][son])
                   next[now][son] = newNode() ;
              now = next[now][son] ;
         }
         cnt[now]++ ;
    }

    void buildAC(){
         std::queue<int> q ;
         fail[root] = root ;
         for(int son = 0 ; son < alphaSize ; son++){
            if(! next[root][son]) next[root][son] = root ;
            else{
                fail[next[root][son]] = root ;
                q.push(next[root][son]) ;
            }
         }
         while(! q.empty()){
            int now = q.front() ; q.pop() ;
            for(int son = 0 ; son < alphaSize ; son++){
                if(! next[now][son])
                    next[now][son] = next[fail[now]][son] ;
                else{
                    fail[next[now][son]] = next[fail[now]][son] ;
                    q.push(next[now][son]) ;
                }
            }

         }
    }

    int query(char *s){
        int now = root ;
        int res = 0 ;
        for(int i = 0 ; s[i] ; i++){
            now = next[now][s[i]-'a'] ;
            int u = now ;
            while(u != root && cnt[u]){
                res += cnt[u] ;
                cnt[u] = 0 ;
                u = fail[u] ;
            }
        }
        return res ;
    }
};

AC ac ;

char word[50] , ask[1000008] ;
int main(){
    int t , n ;
    scanf("%d" , &t) ;
    while(t--){
        scanf("%d" , &n) ;
        ac.clear() ;
        while(n--){
            scanf("%s" ,word) ;
            ac.add(word) ;
        }
        scanf("%s" , ask) ;
        ac.buildAC() ;
        printf("%d\n" , ac.query(ask)) ;
    }

    return 0;
}

你可能感兴趣的:(hdu2222AC自动机)