【AC自动机】AC自动机模板

感谢 小白菜菜菜 的更正,让我可以拥有更简洁的模板!

参考:AC自动机总结

代码如下:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;

const int N = 5e5+5, M = 1e6+5;
struct Trie {
    Trie *next[26];
    Trie *fail;
    int val;
}tree[N];
queue <Trie *> q;
int idx[128];


class ac_auto {
    private:
        int nxt;
        Trie *root;
    public:
        ac_auto() {
            nxt = 0;
            root = add();
        }
        Trie *add() {
            memset(&tree[nxt], 0, sizeof(Trie));
            return &tree[nxt++];
        }
        void insert(char *s) {
            Trie *rt = root;
            int len = strlen(s);
            for(int i = 0; i < len; i++) {
                int c = idx[s[i]+0];
                if(!rt->next[c])
                    rt->next[c] = add();
                rt = rt->next[c];
            }
            rt->val = 1;//rt->val++;用于统计
        }
        void get_f() {
            queue <Trie *> q;
            q.push(root);
            root->fail = NULL;
            while(!q.empty()) {
                Trie *u = q.front(); q.pop();
                for(int c = 0; c < 26; c++) {
                    if(u->next[c]) {
                        Trie *f = u->fail;
                        while(f && !f->next[c]) f = f->fail;
                        if(!f) u->next[c]->fail = root;
                        else u->next[c]->fail = f->next[c];
                        u->next[c]->val |= u->next[c]->fail->val;//状态合并,根据具体题意,不能用于统计
                        q.push(u->next[c]);
                    }
                    else if(u == root) u->next[c] = root;
                    else u->next[c] = u->fail->next[c];
                }
            }
        }
        int match(char *s) {
            Trie *rt = root;
            int len = strlen(s), ret = 0;
            for(int i = 0; i < len; i++) {
                int c = idx[s[i]+0];
                rt = rt->next[c];
                Trie *p = rt;
                while(p && p->val) {
                    ret += p->val;
                    //p->val = 0;统计的时候要清零
                    p = p->fail;
                }
            }
            return ret;
        }
};

void haxi()
{
    for(int i = 0; i < 26; i++) 
        idx['a'+i] = i;
}

int main()
{
    haxi();
    int T, m;
    char str[M];
    scanf("%d", &T);
    while(T--) {
        ac_auto ac;
        scanf("%d", &m);
        while(m--) {
            scanf("%s", str);
            ac.insert(str);
        }
        ac.get_f();
        scanf("%s", str);
        int ans = ac.match(str);
        printf("%d\n", ans);
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值