Keywords Search HDU - 2222 -AC自動機

 

#include<bits/stdc++.h>
using namespace std;
#define maxn 567891
int ans,cnt,nxt[maxn],t,n;
int tree[maxn][32],bo[maxn];
void made(char *s)
{
    int u=1,len=strlen(s);
    for(int i=0; i<len; i++)
    {
        int c=s[i]-'a';
        if(!tree[u][c])
        {
            tree[u][c]=++cnt;
            memset(tree[cnt],0,sizeof(tree[cnt]));
        }
        u=tree[u][c];
    }
    bo[u]++;
}
void bfs()
{
    for(int i=0; i<=25; i++)
        tree[0][i]=1;
    queue<int>q;
    q.push(1);
    nxt[1]=0;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=0; i<=25; i++)
        {
            if(!tree[u][i])
                tree[u][i]=tree[nxt[u]][i];
            else
            {
                q.push(tree[u][i]);
                int v=nxt[u];
                nxt[tree[u][i]]=tree[v][i];
            }
        }
    }
}
void fond(char *s)
{
    int u=1,len=strlen(s),c,k;
    for(int i=0; i<=len; i++)
    {
        c=s[i]-'a';
        k=tree[u][c];
        while(k>1)
        {
            ans+=bo[k];
            bo[k]=0;
            k=nxt[k];
        }
        u=tree[u][c];
    }
    return ;
}
int main()
{
    char str[maxn*2];
    scanf("%d",&t);
    while(t--)
    {
        ans=0;
        cnt=1;
        memset(bo,0,sizeof(bo));
        for(int i=0; i<26; i++)tree[0][i]=tree[1][i]=0;
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
        {
            scanf("%s",str);
            made(str);
        }
        bfs();
        scanf("%s",str);
        fond(str);
        printf("%d\n",ans);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章