ac自动机模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define M 26
int n;
char s1[100009],s[1000009];
struct node
{
    node* fail;
    node* next[M];
    int cnt;
    node() //构造函数
    {
        fail = NULL;
        for(int i=0;i<26;i++)
        {
            next[i]=NULL;
        }
        cnt = 0;
    }
};
void insert_ac(char* p,node* root)
{
    node* tmp = root;
    int l = strlen(p);
    for(int i = 0;i < l;i++)
    {
        int k = p[i] - 'a';
        if(tmp->next[k] == NULL) tmp->next[k] = new node();
        tmp = tmp->next[k];
    }
    tmp->cnt++;
}
void build_fail(node* root)
{
    queue<node*> q;
    q.push(root);
    while(!q.empty())
    {
        node* tmp = q.front();
        q.pop();
        node* p = NULL;
        for(int i = 0;i < M;i++) //构造tmp->next[i]的fail指针
        {
            if(tmp->next[i] != NULL) //出现过
            {
                if(tmp == root) tmp->next[i]->fail = root;
                else
                {
                    p = tmp->fail; //父节点的fail指针
                    while(p != NULL)
                    {
                        if(p->next[i] != NULL) //有跟该字符一样的
                        {
                            tmp->next[i]->fail = p->next[i]; //将fail指针指向那个位置
                            break;
                        }
                        p = p->fail;
                    }
                    if(p == NULL) tmp->next[i]->fail = root;
                }
                q.push(tmp->next[i]);
            }
        }
    }
}
int search_ac(char* s,node* root)
{
    int ans = 0;
    int l = strlen(s);
    node* p = root;
    for(int i = 0;i < l;i++)
    {
        int index = s[i] - 'a';
        while(p->next[index] == NULL && p != root) p = p->fail; //如果不匹配去失败指针指向的字符继续匹配,直到匹配或者到root
        p = p->next[index];
        if(p == NULL) p = root;
        node* tmp = p;
        while(tmp != root && tmp->cnt != -1) //根据题目意思防止同一个模式串记了两次
        {
            ans += tmp->cnt;
            tmp->cnt = -1;
            tmp = tmp->fail;
        }
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        node* root = new node();
        while(n--)
        {
            scanf("%s",s1);
            insert_ac(s1,root);
        }
        build_fail(root);
        scanf("%s",s);
        printf("%d\n",search_ac(s,root));
    }
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值