「一题多解」多模匹配(AC自动机 / 暴力)

引子

难道模版题也可以一题多解?答案是:当然可以。
只要仔细分析题目性质并揣测出题人造数据的方法,就能用简单的暴力通过模版题。

但是,切记一点,正式比赛时为了准确性和速度,千万不要使用非主流解法。


题目链接

本人 AC A C 的是洛谷的 AC A C 自动机模版。
【模板】AC自动机(简单版)


解法一(384 ms)

AC自动机直接上。
具体可以参考这篇博客

代码

本人写的是指针版。

// Template of Aho-Corasick Automaton (Deterministic Finite Automaton)
#include <cstdio>
#include <cstring>
const int maxn = 1000005;
const int maxm = 26;
struct node {
    int cnt;
    node *fail, *next[26];
    void init() {
        cnt = 0, fail = NULL;
        memset(next, NULL, sizeof(next));
    }
} nodes[maxn], *que[maxn];
struct dfa {
    int e;
    node *root;
    node* _add() {
        nodes[e].init();
        return &nodes[e++];
    }
    void init() {
        e = 0;
        root = _add();
    }
    void insert(char *s) {
        node *u = root;
        for (int i = 0, ch; s[i]; i++) {
            ch = s[i] - 'a';
            if (u -> next[ch] == NULL) {
                u -> next[ch] = _add();
            }
            u = u -> next[ch]; 
        }
        u -> cnt++;
    }
    void getfail() {
        root -> fail = root;
        int h = 0, t = 0;
        node *u;
        for (int i = 0; i < maxm; i++) {
            if (root -> next[i]) {
                root -> next[i] -> fail = root;
                que[t++] = root -> next[i];
            } else {
                root -> next[i] = root;
            }
        }
        while (h < t) {
            u = que[h++];
            for (int i = 0; i < maxm; i++) {
                if (u -> next[i]) {
                    u -> next[i] -> fail = u -> fail -> next[i];
                    que[t++] = u -> next[i];
                } else {
                    u -> next[i] = u -> fail -> next[i];
                }
            }
        }
    }
    int match(char *s) {
        int ch, ans = 0;
        node *u = root, *tmp;
        for (int i = 0; s[i]; i++) {
            ch = s[i] - 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值