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

题意:给你n个字符串,最后一行输入一个字符串,问最后一个字符串中出现了几个前面的字符串。


思路:AC自动机模板题。AC自动机详解见点击打开链接


模板:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;

/****************************************************/
const int LetterSize = 26;
const int TrieSize = 10000*50+5;

int tot, root, fail[TrieSize], val[TrieSize], Next[TrieSize][LetterSize];
int newnode(void)
{
    memset(Next[tot], -1, sizeof(Next[tot]));
    val[tot] = 0;
    return tot++;
}

void init(void)
{
    tot = 0;
    root = newnode();
}

int getidx(char x)
{
    return x-'a';
}

void insert(char *ss)
{
    int len = strlen(ss);
    int now = root;
    for(int i = 0; i < len; i++)
    {
        int idx = getidx(ss[i]);
        if(Next[now][idx] == -1)
            Next[now][idx] = newnode();
        now = Next[now][idx];
    }
    val[now]++;	//和Trie一样,根据需要而变
}

void build(void)
{
    queue<int> Q;
    fail[root] = root;
    for(int i = 0; i < LetterSize; i++)
    {
        if(Next[root][i] == -1)
            Next[root][i] = root;
        else
            fail[Next[root][i]] = root, Q.push(Next[root][i]);
    }
    while(!Q.empty())
    {
        int now = Q.front(); Q.pop();
        for(int i = 0; i < LetterSize; i++)
        {
            if(Next[now][i] == -1)
                Next[now][i] = Next[fail[now]][i];
            else
                fail[Next[now][i]] = Next[fail[now]][i], Q.push(Next[now][i]);
        }
    }
}

int match(char *ss)
{
    int len = strlen(ss), now = root, res = 0;
    for(int i = 0; i < len; i++)
    {
        int idx = getidx(ss[i]);
        int tmp = now = Next[now][idx];
        while(tmp)
        {
            res += val[tmp];
            val[tmp] = 0;
            tmp = fail[tmp];
        }
    }
    return res;
}

/*************************************************/
const int maxn = 1e6+5;
char str[maxn], tmp[maxn];

int main(void)
{
    int t, n;
    cin >> t;
    while(t--)
    {
        init();
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
            scanf(" %s", tmp), insert(tmp);
        build();
        scanf(" %s", str);
        printf("%d\n", match(str));
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值