AC自動機

ac自動機是kmp的高級版,實現多模式串匹配。

代碼:

struct AC{
    int next[500005][26], fail[500005], word[500005], Q[500005];
    int root, tol;
 
    int newNode(){
        for(int i = 0; i < 26; i++)
            next[tol][i] = -1;
        word[tol++] = 0;
        return tol - 1;
    }
 
    void Init(){
        tol = 0;
        root = newNode();
    }

    void Insert(char s[]){
        int now = root;
        for(int i = 0, k; s[i] ;i++){
            k = s[i]-'a';
            if(next[now][k] == -1)
                next[now][k] = newNode();
            now = next[now][k];
        }
        /*
        根據要求對word進行處理
        Solve(word[now])
        */
    }
 
    void build(){
        int front, rear;
        front = rear = 0;
        for(int i=0;i<26;i++){
            if(next[root][i]==-1)
                next[root][i] = root;
            else
            {
                fail[next[root][i]] = root;
                Q[rear++] = next[root][i];
            }
        }
        while(front < rear){
            int now = Q[front++];
            for(int i = 0; i < 26; i++){
                if(next[now][i] == -1)
                    next[now][i] = next[fail[now]][i];
                else{
                    fail[next[now][i]] = next[fail[now]][i];
                    Q[rear++]=next[now][i];
                }
            }
        }
    }
 
    int Search(char s[]){
        int now = root, res = 0;
        for(int i = 0, k; s[i] ;i++){
            k = s[i] - 'a';
            now = next[now][k];
            int tmp = now;
            while(tmp != root){
                /*
                ......
                根據不同條件,獲得不同的信息
                ......
                */
                tmp = fail[tmp];
            }
        }
        return res;
    }
 
}ac;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章