HDU 2222 Keywords Search ac自动机模板

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2222

题意:给一些模式串,最后一个目标串,问目标串中模式串的个数

思路:ac自动机模板题,存个档

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define debug puts("here")
using namespace std;

const int N = 1000010;
struct node
{
    node *fail;
    node *next[26];
    int cnt;
    node()
    {
        fail = NULL;
        memset(next, 0, sizeof next);
        cnt = 0;
    }
}*que[N];
char s[60], str[N];

void _insert(char *s, node *root)
{
    node *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        if(p -> next[j] == NULL)
            p -> next[j] = new node();
        p = p -> next[j];
    }
    p -> cnt++;
}
void create_fail(node *root)
{
    int head = 0, tail = 0;
    que[tail++] = root;
    while(head != tail)
    {
        node *p = que[head++];
        node *tmp = NULL;
        for(int i = 0; i < 26; i++)
        {
            if(p -> next[i] != NULL)
            {
                if(p == root) p -> next[i] -> fail = root; //root的子节点的fail指针必定指向root
                else
                {
                    tmp = p -> fail;
                    while(tmp != NULL)
                    {
                        if(tmp -> next[i] != NULL) //找到匹配
                        {
                            p -> next[i] -> fail = tmp -> next[i];
                            break;
                        }
                        tmp = tmp -> fail;
                    }
                    if(tmp == NULL) p -> next[i] -> fail = root; //匹配为空则从root重新匹配
                }
                que[tail++] = p -> next[i];
            }
        }
    }
}
int query(char *s, node *root)
{
    int cnt = 0;
    node *p = root;
    for(int i = 0; s[i]; i++)
    {
        int j = s[i] - 'a';
        while(p -> next[j] == NULL && p != root) //与当前点不匹配,跳转到失败指针
            p = p -> fail;
        p = p -> next[j];
        if(p == NULL) p = root;
        node *tmp = p;
        while(tmp != root && tmp -> cnt != -1)
        {
            cnt += tmp -> cnt;
            tmp -> cnt = -1;
            tmp = tmp -> fail;
        }
    }
    return cnt;
}
int main()
{
    int t, n;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        node *root = new node;
        for(int i = 0; i < n; i++)
        {
            scanf("%s", s);
            _insert(s, root);
        }
        create_fail(root);
        scanf("%s", str);
        printf("%d\n", query(str, root));
    }
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值