Hetao P3804 Cut 题解 [ 蓝 ] [ AC 自动机 ] [ 差分 ]

Cut:AC 自动机简单题。

image

image

思路

看见多个模式串以及求前缀,很显然能想到构建一个 AC 自动机。

那么在用 T 查询时,当前指针的深度就是该位置的最长前缀匹配长度。这个在字典树 insert 的时候就能求出来。

求出每一位的最长前缀后,因为这些部分都不能作为分割点,所以将这些区域用差分区间加,最后求出没有被加过的位置的个数 x,答案即为 2x。因为每个分割点可选可不选。

时间复杂度 O(n||)

注意 AC 自动机要 build 后再 query,不然你会和我一样虚空调试 10min。

代码

#include <bits/stdc++.h>
#define fi first
#define se second
#define lc (p<<1)
#define rc ((p<<1)|1)
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
using pi=pair<int,int>;
const ll mod=998244353;
char t[1000005],s[1000005];
int n,ch[1000005][30],ne[1000005],dep[1000005],idx=0;
ll f[1000005],ans=1;
void insert(char *s)
{
    int p=0;
    for(int i=1;s[i];i++)
    {
        int c=s[i]-'a';
        if(ch[p][c]==0)ch[p][c]=++idx;
        p=ch[p][c];
        dep[p]=i;
    }
}
void build()
{
    queue<int>q;
    for(int i=0;i<26;i++)
    {
        if(ch[0][i])q.push(ch[0][i]);
    }
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=0;i<26;i++)
        {
            int v=ch[u][i];
            if(v)ne[v]=ch[ne[u]][i],q.push(v);
            else ch[u][i]=ch[ne[u]][i];
        }
    }
}
void query(char *s)
{
    int p=0;
    for(int i=1;s[i];i++)
    {
        int c=s[i]-'a';
        p=ch[p][c];
        int len=dep[p];
        if(len)
        {
            f[i]--;
            f[i-len+1]++;
        }
    }
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>t+1>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>s+1;
        insert(s);
    }
    build();
    query(t);
    int lt=strlen(t+1);
    for(int i=1;i<lt;i++)
    {
        f[i]+=f[i-1];
        if(f[i]==0)ans=(ans*2)%mod;
    }
    cout<<ans;
    return 0;
}
posted @   KS_Fszha  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示