首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >洛谷P3808 【模板】AC自动机(简单版)

洛谷P3808 【模板】AC自动机(简单版)

作者头像
attack
发布2018-07-27 15:04:49
6020
发布2018-07-27 15:04:49
举报

题目背景

这是一道简单的AC自动机模板题。

用于检测正确性以及算法常数。

为了防止卡OJ,在保证正确的基础上只有两组数据,请不要恶意提交。

管理员提示:本题数据内有重复的单词,且重复单词应该计算多次,请各位注意

题目描述

给定n个模式串和1个文本串,求有多少个模式串在文本串里出现过。

输入输出格式

输入格式:

第一行一个n,表示模式串个数;

下面n行每行一个模式串;

下面一行一个文本串。

输出格式:

一个数表示答案

输入输出样例

输入样例#1: 复制

2
a
aa
aa

输出样例#1: 复制

2

说明

subtask1[50pts]:∑length(模式串)<=10^6,length(文本串)<=10^6,n=1;

subtask2[50pts]:∑length(模式串)<=10^6,length(文本串)<=10^6;

感觉AC自动机比后缀自动机好理解多了qwq

就是把匹配串的trie树建出来然后跑一下匹配

// luogu-judger-enable-o2
// luogu-judger-enable-o2
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int MAXN = 1e6 + 10;
char s[MAXN];
int N;
int ch[MAXN][26], fail[MAXN], val[MAXN], tot = 0, root = 0;
void insert(char *s) {
    int len = strlen(s + 1), now = root;
    for(int i = 1; i <= len; i++) {
        int x = s[i] - 'a';
        if(!ch[now][x]) ch[now][x] = ++tot;
        now = ch[now][x];
    }
    val[now]++;
}
void GetFail() {
    queue<int> q; 
    for(int i = 0; i <= 25; i++) 
        if(ch[root][i]) q.push(ch[root][i]);
    while(!q.empty()) {
        int p = q.front(); q.pop();
        for(int i = 0; i <= 25; i++) {
            if(!ch[p][i]) ch[p][i] = ch[fail[p]][i];
            else fail[ch[p][i]] = ch[fail[p]][i], q.push(ch[p][i]);
        }
    }
}
int Find(char *s) {
    int len = strlen(s + 1);
    int now = root, ans = 0;
    for(int i = 1; i <= len; i++) {
        int x = s[i] - 'a';
        now = ch[now][x];
        for(int t = now; t && ~val[t]; t = fail[t]) ans += val[t], val[t] = -1;
    }
    return ans;
}
int main() {
#ifdef WIN32
    freopen("a.in", "r", stdin);
#endif
    scanf("%d", &N);
    for(int i = 1; i <= N; i++) {
        scanf("%s", s + 1);
        insert(s);
    }
    GetFail();
    scanf("%s", s + 1);
    printf("%d", Find(s));
    return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-06-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目背景
  • 题目描述
  • 输入输出格式
  • 输入输出样例
  • 说明
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档