HDU 2222 - Keywords Search(AC自动机模板)

题目链接:

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

题解:

AC自动机模板,丢个模板就跑,真刺激

AC代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int kind = 26;

struct node
{
    node* fail;
    node* nxt[kind];
    int count;
    node()
    {
        fail = NULL;
        count = 0;
        memset(nxt, NULL , sizeof(nxt));
    }
}*q[500001];

char keyword[51];
char str[1000001];
int head, tail;

void insert(char *str , node *root)
{
    node *p = root;
    int i = 0, index;
    while(str[i])
    {
        index = str[i] - 'a';
        if(p -> nxt[index] == NULL)
            p -> nxt[index] = new node();
        p = p -> nxt[index];
        i++;
    }
    p -> count++;
}

void build_AC_Tree(node *root)
{
    root -> fail = NULL;
    q[head++] = root;
    while(head != tail)
    {
        node* temp = q[tail++];
        node* p = NULL;
        for(int i = 0; i< 26; i++)
        {
            if(temp -> nxt[i] != NULL)
            {
                if(temp == root)
                    temp -> nxt[i] -> fail = root;
                else
                {
                    p = temp -> fail;
                    while(p != NULL)
                    {
                        if(p -> nxt[i] != NULL)
                        {
                            temp -> nxt[i] -> fail = p -> nxt[i];
                            break;
                        }
                        p = p -> fail;
                    }
                    if(p == NULL)
                        temp -> nxt[i] -> fail = root;
                }
                q[head++] = temp -> nxt[i];
            }
        }
    }
}

int query(node* root)
{
    int i = 0, cnt = 0, index, len = strlen(str);
    node* p = root;
    while(str[i])
    {
        index = str[i] - 'a';
        while(p -> nxt[index] == NULL && p != root)
            p = p-> fail;
        p = p-> nxt[index];
        p = (p == NULL)? root:p;
        node *temp = p;
        while(temp != root && temp -> count != -1)
        {
            cnt += temp -> count;
            temp -> count = -1;
            temp = temp -> fail;
        }
        i ++;
    }
    return cnt;
}

int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        head = tail = 0;
        node* root = new node();
        scanf("%d", &n);
        getchar();
        while(n --)
        {
            gets(keyword);
            insert(keyword, root);
        }
        build_AC_Tree(root);
        scanf("%s",str);
        printf("%d\n",query(root));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值