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

第一次听说AC自动机的时候的确吓尿了。以为是能直接AC题目的程序(那岂不是开挂。。)

后来学了KMP,才知道原来是字符串处理的一种算法(据说孙老师教的是自动机理论 不知道是不是就是字符串匹配)

这题就是一道裸题,AC自动机跟KMP的差别就在于 AC自动机是在一个母串中匹配多个子串(把这些子串做成trie树)而KMP则是在一个母串中找一个子串(利用失配数组)


其实本质上是差不多的,只是实现方法不太一样(虽然我也是抄的模版。。)


好了 献上代码(其实就是照抄的模版。。给跪)


#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1000005;
struct trie{
    int sum,fail,son[26];
    int flag;
}tree[N];
int sz,ans,n;
char des[N];
void in(char *word){
    int p = 0;
    for(int i=0;word[i];i++){
        int t = word[i]-'a';
        if(!tree[p].son[t])
            tree[p].son[t] = ++sz;
        p = tree[p].son[t];
    }
    tree[p].sum++;
}
void build_acauto(){
    queue<int> q;
    for(int i=0;i<26;i++)
        if(tree[0].son[i])
            q.push(tree[0].son[i]);
    while(!q.empty()){
        int p = q.front();
        q.pop();
        for(int i=0;i<26;i++){
            int t = tree[p].son[i];
            if(!t)continue;
            int f = tree[p].fail;
            while(f&&!tree[f].son[i])
                f = tree[f].fail;
            tree[t].fail = tree[f].son[i];
            q.push(t);
        }
    }
}
int query_acauto(char *word){
    int p = 0,ret = 0;
    for(int i=0;word[i];i++){
        int t = word[i] - 'a';
        while(p&&!tree[p].son[t])
            p = tree[p].fail;
        p = tree[p].son[t];
        int temp = p;
        while(temp&&!tree[temp].flag){
            ret += tree[temp].sum;
            tree[temp].flag = 1;
            temp = tree[temp].fail;
        }
    }
    return ret;
}
void init(){
    for(int i=0;i<=sz;i++){
        tree[i].sum = tree[i].fail = tree[i].flag= 0;
        for(int j=0;j<26;j++)
            tree[i].son[j] = 0;
    }
    ans = sz = 0;
}
int main()
{
    int T;
    cin>>T;
    char str[60];
    while(T--){
        init();
        scanf("%d",&n);
        while(n--){
            scanf("%s",str);
            in(str);
        }
        build_acauto();
        scanf("%s",des);
        printf("%d\n",query_acauto(des));
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值