HDU 2222 Keywords Search (AC自動機模版題)

第一次聽說AC自動機的時候的確嚇尿了。以爲是能直接AC題目的程序(那豈不是開掛。。)

後來學了KMP,才知道原來是字符串處理的一種算法(據說孫老師教的是自動機理論 不知道是不是就是字符串匹配)

這題就是一道裸題,AC自動機跟KMP的差別就在於 AC自動機是在一個母串中匹配多個子串(把這些子串做成trie樹)而KMP則是在一個母串中找一個子串(利用失配數組)


其實本質上是差不多的,只是實現方法不太一樣(雖然我也是抄的模版。。)


好了 獻上代碼(其實就是照抄的模版。。給跪)


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1000005;
struct trie{
    int sum,fail,son[26];
    int flag;
}tree[N];
int sz,ans,n;
char des[N];
void in(char *word){
    int p = 0;
    for(int i=0;word[i];i++){
        int t = word[i]-'a';
        if(!tree[p].son[t])
            tree[p].son[t] = ++sz;
        p = tree[p].son[t];
    }
    tree[p].sum++;
}
void build_acauto(){
    queue<int> q;
    for(int i=0;i<26;i++)
        if(tree[0].son[i])
            q.push(tree[0].son[i]);
    while(!q.empty()){
        int p = q.front();
        q.pop();
        for(int i=0;i<26;i++){
            int t = tree[p].son[i];
            if(!t)continue;
            int f = tree[p].fail;
            while(f&&!tree[f].son[i])
                f = tree[f].fail;
            tree[t].fail = tree[f].son[i];
            q.push(t);
        }
    }
}
int query_acauto(char *word){
    int p = 0,ret = 0;
    for(int i=0;word[i];i++){
        int t = word[i] - 'a';
        while(p&&!tree[p].son[t])
            p = tree[p].fail;
        p = tree[p].son[t];
        int temp = p;
        while(temp&&!tree[temp].flag){
            ret += tree[temp].sum;
            tree[temp].flag = 1;
            temp = tree[temp].fail;
        }
    }
    return ret;
}
void init(){
    for(int i=0;i<=sz;i++){
        tree[i].sum = tree[i].fail = tree[i].flag= 0;
        for(int j=0;j<26;j++)
            tree[i].son[j] = 0;
    }
    ans = sz = 0;
}
int main()
{
    int T;
    cin>>T;
    char str[60];
    while(T--){
        init();
        scanf("%d",&n);
        while(n--){
            scanf("%s",str);
            in(str);
        }
        build_acauto();
        scanf("%s",des);
        printf("%d\n",query_acauto(des));
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章