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

题目背景

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

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

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

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

题目描述

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

输入输出格式

输入格式:

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

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

下面一行一个文本串。

输出格式:

一个数表示答案

扫描二维码关注公众号,回复: 2144154 查看本文章

输入输出样例

输入样例#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自动机匹配,匹配时遇到结尾标记,给结尾标记打上记号,最后统计就好了
存在重复的串,两个串就指向同一个结尾的位置,由于我们是给结尾标记所在的点打的记号,那么两个串肯定都会算上的

#include<bits/stdc++.h>
#define ui unsigned int
#define ll long long
#define db double
#define ld long double
#define ull unsigned long long
const int MAXN=1000000+10;
int n,ch[MAXN][30],fail[MAXN],last[MAXN],vis[MAXN],ps[MAXN],ed[MAXN],cnt,ans;
char s[MAXN];
std::queue<int> q;
template<typename T> inline void read(T &x)
{
    T data=0,w=1;
    char ch=0;
    while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
    if(ch=='-')w=-1,ch=getchar();
    while(ch>='0'&&ch<='9')data=((T)data<<3)+((T)data<<1)+(ch^'0'),ch=getchar();
    x=data*w;
}
template<typename T> inline void write(T x,char ch='\0')
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)write(x/10);
    putchar(x%10+'0');
    if(ch!='\0')putchar(ch);
}
template<typename T> inline void chkmin(T &x,T y){x=(y<x?y:x);}
template<typename T> inline void chkmax(T &x,T y){x=(y>x?y:x);}
template<typename T> inline T min(T x,T y){return x<y?x:y;}
template<typename T> inline T max(T x,T y){return x>y?x:y;}
inline void init()
{
    for(register int i=0,lt=strlen(s);i<lt;++i)s[i]-='a'-1;
}
inline void insert(int rk)
{
    int x=0;
    for(register int i=0,lt=strlen(s);i<lt;++i)
        if(!ch[x][s[i]])x=ch[x][s[i]]=++cnt;
        else x=ch[x][s[i]];
    ps[rk]=x;
    ed[x]=1;
}
inline void getfail()
{
    for(register int i=1;i<=26;++i)
        if(ch[0][i])q.push(ch[0][i]);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(register int i=1,y,z;i<=26;++i)
            if(ch[x][i])
            {
                y=ch[x][i],z=fail[x];
                while(z&&!ch[z][i])z=fail[z];
                fail[y]=ch[z][i];
                last[y]=ed[fail[y]]?fail[y]:last[fail[y]];
                q.push(y);
            }
            else ch[x][i]=ch[fail[x]][i];
    }
}
inline void save(int x)
{
    if(x)
    {
        if(ed[x])vis[x]=1;
        save(last[x]);
    }
}
inline void match()
{
    int x=0;
    for(register int i=0,lt=strlen(s);i<lt;++i)x=ch[x][s[i]],save(ed[x]||last[x]?x:0);
}
int main()
{
    read(n);
    for(register int i=1;i<=n;++i)scanf("%s",s),init(),insert(i);
    getfail();
    scanf("%s",s);init();match();
    for(register int i=1;i<=n;++i)
        if(vis[ps[i]])ans++;
    write(ans,'\n');
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/hongyj/p/9301996.html