【AC自动机 && 各个单词在文本中出现次数(可重叠)】HDU - 3065 病毒侵袭持续中

本文介绍了一种使用AC自动机进行高效文本匹配的方法,包括自动机的构建、匹配过程及其实现代码。适用于大规模文本中查找多个关键词的应用场景。

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

Step1 Problem:

给你 n 个单词,一个文本串。
问你每个单词在文本串中出现的次数(可重叠),没有出现过的不需要输出。
数据范围:
1<=单词长度<=50, 1<=n<=1000, 文本串 <= 2e6.

Step2 Ideas:

匹配的时候,需要判断该后缀是否也是一个单词,所以需要走到 fail 指针所指位置。

Step3 Code:

#include<bits/stdc++.h>
using namespace std;
const int N = 5e4+50;
const int M = 2e6+5;
struct node
{
    int id;
    node *next[26], *fail;
};
node a[N];
char str[1005][55];
char s[M];
int ans[1005];
int top;
node *creat_kong()
{
    node *root = &a[top++];
    root->id = 0;
    for(int i = 0; i < 26; i++)
        root->next[i] = NULL;
    root->fail = NULL;
    return root;
}
void Insert(node *root, char *s, int id)
{
    node *p = root;
    int len = strlen(s);
    for(int i = 0; i < len; i++)
    {
        int tmp = s[i] - 'A';
        if(!p->next[tmp]) p->next[tmp] = creat_kong();
        p = p->next[tmp];
    }
    p->id = id;
}
void get_fail(node *root)
{
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        node *p = q.front(); q.pop();
        for(int i = 0; i < 26; i++)
        {
            if(!p->next[i]) continue;
            node *tmp = p->fail;
            while(tmp && !tmp->next[i]) tmp = tmp->fail;
            if(!tmp) p->next[i]->fail = root;
            else p->next[i]->fail = tmp->next[i];
            q.push(p->next[i]);
        }
    }
}
void mat(node *root, char *s)
{
    int len = strlen(s);
    node *p = root;
    for(int i = 0; i < len; i++)
    {
        if(s[i] < 'A' || s[i] > 'Z') {
            p = root;
            continue;
        }
        int tmp = s[i]-'A';
        while(p != root && !p->next[tmp]) p = p->fail;
        if(p == root && !p->next[tmp]) continue;
        p = p->next[tmp];
        node *t = p;
        while(t != root)
        {
            if(t->id)//判断当前位置对应的单词是否存在
            ans[t->id]++;
            t = t->fail;
        }
    }
}
int main()
{

    int n;
    while(~scanf("%d", &n))
    {
        top = 0;
        node *root = creat_kong();
        for(int i = 1; i <= n; i++)
        {
            scanf("%s", str[i]);
            Insert(root, str[i], i);
        }
        get_fail(root);
        memset(ans, 0, sizeof(ans));
        scanf("%s", s);
        mat(root, s);
        for(int i = 1; i <= n; i++)
        {
            if(ans[i]) printf("%s: %d\n", str[i], ans[i]);
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值