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

这篇博客介绍了一种利用AC自动机算法解决文本中字符串统计问题的方法。首先,通过建立字典树来存储给定字符串,然后计算Fail数组以实现快速查找。在查询阶段,利用Fail数组递归寻找匹配的前缀并统计贡献。代码示例展示了整个过程,包括AC自动机的构建和查询操作。
摘要由CSDN通过智能技术生成

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2222

HDU 2222 Keywords Search

题意

        统计一个文本串中出现过多少个给定的字符串,每个给定的字符串只统计一次。

思路

        这是AC自动机裸题,先将给定的字符串建字典树,接着计算Fail数组的值,然后用Fail来递归寻找出现过的前缀,统计贡献就好了,注意统计贡献的时候要将贡献清空,否则一个字符串将统计多次。

代码

#include <bits/stdc++.h>
using namespace std;

const int maxn=5e5+10;

struct ACTire
{
    int tree[maxn][26],fail[maxn],end_[maxn];//end_数组一般表示是否为结束字符
    int root,cnt;
    int newcode(){
        for(int i=0;i<26;i++) tree[cnt][i]=-1;
        end_[cnt++]=0;
        return cnt-1;
    }
    void init(){
        cnt=0;
        root=newcode();
    }
    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]=newcode();
            pos=tree[pos][id];
        }
        end_[pos]++;
    }
    //计算fail数组
    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'];
            int temp=now;
            while(temp!=root){
                res+=end_[temp];
                end_[temp]=0;//因为每个单词只统计一次而且只有一个查询,重置为0,
                temp=fail[temp];
            }
        }
        return res;
    }
}ac;

char s[maxn*2];

int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        ac.init();
        for(int i=1;i<=n;i++){
            scanf("%s",s);
            ac.insert_(s);
        }
        ac.build();
        scanf("%s",s);
        printf("%d\n",ac.query(s));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值