hdu2896AC自动机

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

const int nodeSize = 200*500 + 8 ;
const int alphaSize = 130 ;
struct AC{
    int next[nodeSize][alphaSize] ;
    int lable[nodeSize] ;
    int fail[nodeSize] ;
    int totel ;
    int root ;

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

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

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

    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]) ;
                }
            }

         }
    }

    std::vector<int> query(char *s){
        int now = root ;
        std::vector<int> res  ;
        for(int i = 0 ; s[i] ; i++){
            now = next[now][s[i]-' '] ;
            int u = now ;
            while(u != root){
                if(lable[u]) res.push_back(lable[u]) ;
                u = fail[u] ;
            }
        }
        std::sort(res.begin() , res.end()) ;
        return res ;
    }
};

AC ac ;

char word[200] , ask[10008] ;
int main(){
    int n , m , sum ;
    while(scanf("%d" , &n) != EOF){
        ac.clear() ;
        for(int i = 1 ; i <= n ; i++){
            scanf("%s" ,word) ;
            ac.add(word , i ) ;
        }
        ac.buildAC() ;
        sum = 0 ;
        scanf("%d" , &m) ;
        for(int i = 1 ; i <= m ; i++){
            scanf("%s" , ask) ;
            std::vector<int> res = ac.query(ask) ;
            if(! res.empty()){
                sum++ ;
                printf("web %d:" , i) ;
                for(std::vector<int>::iterator it = res.begin() ; it != res.end() ; it++)
                    printf(" %d" , *it) ;
                puts("") ;
            }
        }
        printf("total: %d\n" , sum)  ;
    }
    return 0;
}

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