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

HDU2222
题意就是统计一个文本串中出现过多少个给定的字符串,每个给定的字符串只统计一次。
这就是AC自动机的裸题,我们直到AC自动机的精髓在于状态转移,我们可以从k状态转移到k+1的状态,所以我们只需要把文本串放到AC自动机上面沿着Trie树跑,然后用Fail来递归寻找出现过的前缀,统计贡献就好了,注意统计贡献的时候要将贡献清空,否则一个字符串将统计多次
HDU2222代码

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<queue>
#include<stdlib.h>
using namespace std;
const int maxn = 5e5+5;
struct ACTrie
{
    int tree[maxn][26],fail[maxn],end_[maxn];
    int root,cnt;
    int newnode()
    {
        for(int i=0;i<26;i++)
            tree[cnt][i]=-1;
        end_[cnt++]=0;
        return cnt-1;
    }
    void init()
    {
        cnt=0;
        root=newnode();
    }
    void insert_(char str[])
    {
        int len= strlen(str);
        int pos=root;
        for(int i=0;i<len;i++)
        {
            int id=str[i]-'a';
            if(tree[pos][id]==-1)
                tree[pos][id]=newnode();
            pos=tree[pos][id];
        }
        end_[pos]++;
    }
    void build()
    {
        queue<int> que;
        fail[root]=root;
        for(int i=0;i<26;i++)
        {
            if(tree[root][i]==-1) tree[root][i]=root;
            else
            {
                fail[tree[root][i]]=root;
                que.push(tree[root][i]);
            }
        }
        while(!que.empty())
        {
            int now=que.front();
            que.pop();
            for(int i=0;i<26;i++)
            {
                if(tree[now][i]==-1)
                    tree[now][i]=tree[fail[now]][i];
                else
                {
                    fail[tree[now][i]]=tree[fail[now]][i];
                    que.push(tree[now][i]);
                }
            }
        }
    }
    int query(char str[])
    {
        int len=strlen(str);
        int now=root;
        int res=0;
        for(int i=0;i<len;i++)
        {
            now=tree[now][str[i]-'a'];//在Trie上不断向后跑
            int temp=now;
            while(temp!=root)
            {
                res+=end_[temp];
                end_[temp]=0;
                temp=fail[temp];
            }
        }
        return res;
    }
};
char str[maxn*2];
ACTrie ac;
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        ac.init();
        for(int i=0;i<n;i++)
        {
            scanf("%s",str);
            ac.insert_(str);
        }
        ac.build();
        scanf("%s",str);
        printf("%d\n",ac.query(str));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38891827/article/details/80684071