// hdu2222 // AC自动机初学

// hdu2222 //
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
char k[55],s[1000005];
struct node
{
    int fail;
    int next[26];
    int cnt;
    void newnode()
    {
        cnt=0;
        fail=-1;
        for(int i=0;i<26;i++)
        {
            next[i]=-1;
        }
    }
}t[500005];
int root=0,tot=0;
void insert(char *str)
{
    int p=root;
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(t[p].next[id] == -1)
        {
            t[++tot].newnode();
            t[p].next[id] = tot;
        }
        p = t[p].next[id];
    }
    t[p].cnt++;
}
void build_ac()
{
    queue<int>q;
    q.push(root);
    while(!q.empty())
    {
        int p=q.front();
        q.pop();
        for(int i=0;i<26;i++)
        {
            if(t[p].next[i] != -1)
            {
                q.push(t[p].next[i]);
                if(p==root)
                {
                    t[t[p].next[i]].fail = root;
                }
                else
                {
                    int k = t[p].fail;
                    while(k!=-1)
                    {
                        if(t[k].next[i] != -1)
                        {
                            t[t[p].next[i]].fail = t[k].next[i];
                            break;
                        }
                        k = t[k].fail;
                    }
                    if(k == -1)
                    {
                        t[t[p].next[i]].fail = root;
                    }
                }
            }
        }
    }
}
int query()
{
    int res=0,len=strlen(s);
    int p=root;
    for(int i=0;i<len;i++)
    {
        int id=s[i]-'a';
        while(t[p].next[id] == -1 && p!=root)
        {
            p = t[p].fail;
        }
        p = t[p].next[id];
        if(p==-1)
        {
            p=root;
        }
        int k=p;
        while(k!=root && t[k].cnt>0)
        {
            res+=t[k].cnt;
            t[k].cnt=-1;
            k = t[k].fail;
        }
    }
    return res;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n;
        scanf("%d",&n);
        tot=0;
        t[root].newnode();
        for(int i=1;i<=n;i++)
        {
            scanf("%s",k);
            insert(k);
        }
        build_ac();
        scanf("%s",s);
        printf("%d
",query());
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wikioibai/p/4471482.html