HUD2222(ac自动机)

本文介绍了一道标准AC自动机模板题的实现方法,详细解释了如何构建Trie树、插入字符串、计算失败指针及查找模式串的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标准ac自动机模板题

题目链接:https://vjudge.net/problem/HDU-2222
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
//ac_automaton algorithm

const int MAXNODE = 550000;
const int SIGMA_SIZE = 26;

int fail[MAXNODE]; //失配数组
int last[MAXNODE]; //后缀链接
int ans;

//构造trie
int ch[MAXNODE][SIGMA_SIZE];
int val[MAXNODE];
int sz;
void init()
{
    ans = 0;
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
}

void insert(char *s)
{
    int u = 0;
    int len = strlen(s);

    for(int i = 0; i < len; ++i)
    {
        int c = s[i] - 'a';
        if(!ch[u][c])
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][c] = sz++;
        }
        u = ch[u][c];
    }
    val[u]++;
}


//计算fail指针
void getFail()
{
    queue<int> q;
    fail[0] = 0;
    for(int c = 0; c < SIGMA_SIZE; c++)
    {
        int u = ch[0][c];
        if(u)
        {
            fail[u] = 0; q.push(u); last[u] = 0;
        }
    }
    while(!q.empty())
    {
        int r = q.front(); q.pop();
        for(int c = 0;c < 26;c++)
        {
            int u = ch[r][c];
            if(!u){ ch[r][c] = ch[fail[r]][c]; continue;}
            q.push(u);
            int v = fail[r];
            while(v && !ch[v][c]) v = fail[v];
            fail[u] = ch[v][c];
            last[u] = val[fail[u]] ? fail[u] : last[fail[u]];
        }
        //cout << last[r] <<endl;
    }
}

void solve(int j)
{
    //cout << j <<endl;
    if(!j) return;
    if(val[j])
    {
        ans += val[j];
        val[j] = 0;
    }
    solve(last[j]);
}
void find(char* T)
{
    int len = strlen(T),j = 0;
    getFail();
    for(int i = 0; i < len; i++)
    {
        j = ch[j][T[i] - 'a'];
        //cout << val[j] <<endl;
        if(val[j]) solve(j);
        else if(last[j]) solve(last[j]);
    }
}

int main()
{
    int t, n;
    char dic[100],str[1100000];
    scanf("%d", &t);
    while(t--)
    {
        init();
        scanf("%d", &n);
        while(n--)
        {
            scanf("%s", dic);
            insert(dic);
        }
        scanf("%s", str);
        find(str);
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值