LuoGu P3808 Aho Corasick Automaton

字符串经典算法

#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
struct Aho_Corasick_Automaton {
    int ch[N][26], f[N], val[N], sz, rt,v[N];
    int newnode() { memset(ch[sz], -1, sizeof(ch[sz])), val[sz] = 0; return sz++; }
    void init() { sz = 0, rt = newnode(); }
    inline int idx(char c) { return c - 'a'; };
    void insert(const char* s) {
        int u = 0;
        for (int i = 0; s[i]; i++) {
            int c = idx(s[i]);
            if (ch[u][c] == -1) ch[u][c] = newnode();
            u = ch[u][c];
        }
        val[u]++;
    }
    void build() {
        queue<int> q;
        f[rt] = rt;
        for (int c = 0; c < 26; c++) {
            if (~ch[rt][c])f[ch[rt][c]] = rt, q.push(ch[rt][c]);
            else ch[rt][c] = rt;
        }
        while (!q.empty()){
            int u = q.front();
            q.pop();
            // val[u] |= val[f[u]];
            for (int c = 0; c < 26; c++){
                if (~ch[u][c])
                    f[ch[u][c]] = ch[f[u]][c], q.push(ch[u][c]);
                else
                    ch[u][c] = ch[f[u]][c];
            }
        }
    }
    //返回主串中有多少模式串
    int query(const char* s)
    {
        int u = rt;
        int res = 0;
        for (int i = 0; s[i]; i++)
        {
            int c = idx(s[i]);
            u = ch[u][c];
            int tmp = u;
            while (tmp != rt&&v[tmp]==0)
            {
                res += val[tmp];
                val[tmp] = 0;
                v[tmp]=1;
                tmp = f[tmp];
            }
        }
        return res;
    }
} aca;
char s[N];
int main() {
    aca.init();
    int n; cin >> n; for (int i = 1; i <= n; ++i)scanf("%s", s), aca.insert(s);
    aca.build();
    scanf("%s", s);
    cout << aca.query(s) << endl;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值