HDU 2222 (AC自动机)

Problem : 给若干个模式串,询问目标串中出现了多少个模式串。
Solution : 复习了一下AC自动机。需要注意AC自动机中的fail,和next的含义。fail指向了一个最长的与当前匹配出具有相同后缀的一个前缀节点,next用来转移下一个字符,指向最远可以匹配的位置。另外,在目标串匹配时,需要用一个temp指针不断经过fail指针向前跳转,所有经过的节点都是符合的。

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;

const int N = 500008;
struct AC_Automan
{
    int next[N][26];
    int fail[N];
    int cnt[N];
    int root, tot;
    int newnode()
    {
        for (int i = 0; i < 26; ++i) next[tot][i] = -1;
        fail[tot] = -1;
        cnt[tot] = 0;
        return tot++;
    }
    void clear()
    {
        tot = 0;
        root = newnode();
    }
    void insert(const string &s)
    {
        int p = root;
        for (int i = 0, len = s.length(); i < len; ++i)
        {
            if (next[p][s[i] - 'a'] == -1) next[p][s[i] - 'a'] = newnode();
            p = next[p][s[i] - 'a'];
        }
        ++cnt[p];
    }
    void build()
    {
        queue <int> Q;
        Q.push(root);
        while (!Q.empty())
        {
            int p = Q.front(); Q.pop();
            for (int i = 0; i < 26; ++i)
            {
                if (~next[p][i])
                {
                    if (p == root) fail[next[p][i]] = root;
                    else fail[next[p][i]] = next[fail[p]][i];
                    Q.push(next[p][i]);
                }
                else
                {   
                    if (p == root) next[p][i] = root;
                    else next[p][i] = next[fail[p]][i];
                }
            }
        }
    }
    int solve(const string &t)
    {
        int p = root, ans = 0;
        for (int i = 0, len = t.length(); i < len; ++i)
        {
            p = next[p][t[i] - 'a'];
            for (int temp = p; temp != root && cnt[temp] != -1; temp = fail[temp])
            {
                ans += cnt[temp];
                cnt[temp] = -1;
            }
        }
        return ans;
    }
}ac;

int main()
{
    cin.sync_with_stdio(0);
    int T; cin >> T;
    for (int cas = 1; cas <= T; ++cas)
    {
        ac.clear();
        int n; cin >> n;
        for (int i = 0; i < n; ++i)
        {
            string s; cin >> s;
            ac.insert(s);
        }
        ac.build();
        string t; cin >> t;
        cout << ac.solve(t) << endl;
    }
}

转载于:https://www.cnblogs.com/rpSebastian/p/7191121.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值