AC自动机模板

struct Aho{
    struct node{
        int next[26];
        int fail,cnt;
    }state[maxn];
    queue<int> q;
    int size;
    int idx(char ch) {return ch - 'a';}
    void init(){
        while(!q.empty()) q.pop();
        for(int i=0; i<maxn; i++){
            memset(state[i].next, 0, sizeof(state[i].next));
            state[i].fail = state[i].cnt = 0;
        }
        size = 1;
    }
    void insert(char *s){
        int n = (int)strlen(s);
        int now = 0;
        for(int i=0; i<n; i++){
            int c = idx(s[i]);
            if(!state[now].next[c]){
                state[now].next[c] = size++;
            }
            now = state[now].next[c];
        }
        vec[now].push_back(id);
        state[now].cnt++;
    }
    void build(){
        state[0].fail = -1;
        q.push(0);//0是根节点
        while(!q.empty()){
            int u = q.front();
            q.pop();
            for(int i=0; i<26; i++){
                if(state[u].next[i]){
                    if(u == 0) state[state[u].next[i]].fail = 0;
                    else{
                        int v = state[u].fail;//父亲的fail
                        while(v != -1){
                            if(state[v].next[i]){//如果该节点的儿子有这条边
                                state[state[u].next[i]].fail = state[v].next[i];
                                break;
                            }
                            v = state[v].fail;
                        }
                        if(v == -1)
                            state[state[u].next[i]].fail = 0;
                    }
                    q.push(state[u].next[i]);
                }
                else{//按照蓝书上的话说 是把不存在的fail也补上 导致match时可以不需要不断往上跳
                    if(u == 0) state[u].next[i] = 0;
                    else state[u].next[i] = state[state[u].fail].next[i];
               }
            }
        }
    }
    int get(int now){
        int ans = 0;
        while(now){
            ans += state[now].cnt;
            state[now].cnt = 0;
            now = state[now].fail;
        }
        return ans;
    }
    int match(char *s){
        int n = (int)strlen(s);
        int now = 0;
        int ans = 0;
        for(int i=0; i<n; i++){
            int c = idx(s[i]);
            if(state[now].next[c])
                now = state[now].next[c];
            else{
                int p = state[now].fail;
                while(p != -1 && state[p].next[c] == 0) p = state[p].fail;
                if(p == -1) now = 0;
                else now = state[p].next[c];
            }
                 ans += get(now);
        }
        return ans;
    }
}aho;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值