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

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


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


模板:

#include
#include
#include
#include
#include
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 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;
}



你可能感兴趣的:(AC自动机)