[BZOJ4566][HAOI2016]找相同字符(后缀自动机)

题目:

我是超链接

题解:

又有点像当时找公共子串的时候了,这个位置不同的也可以一定要扯上right集了
对第一个串建立后缀自动机,然后用第二个串在自动机上进行匹配
sum表示的是当前状态之前fa链上点的总贡献。因为如果匹配到当前的状态,那么fa链上之前的就都被匹配上了。

sum[i]=sum[fa[i]]+(l[fa[i]]l[fa[fa[i]]])right[fa[i]] s u m [ i ] = s u m [ f a [ i ] ] + ( l [ f a [ i ] ] − l [ f a [ f a [ i ] ] ] ) ∗ r i g h t [ f a [ i ] ]

进行匹配的时候匹配到一个节点的贡献为 sum[p]+(tmpl[fa[p]])right[p] s u m [ p ] + ( t m p − l [ f a [ p ] ] ) ∗ r i g h t [ p ]

代码:

#include <cstdio>
#include <cstring>
#define LL long long
using namespace std;
const int N=400005;
int p,np,last,q,nq,cnt,step[N],ch[N*2][30],fa[N],r[N],c[N],a[N];
LL ans,sum[N];char st[N];
void insert(int c)
{
    p=last; last=np=++cnt;
    step[np]=step[p]+1;
    while (p && !ch[p][c]) ch[p][c]=np,p=fa[p];
    if (!p) {fa[np]=1;return;}
    q=ch[p][c];
    if (step[q]==step[p]+1){fa[np]=q;return;}
    nq=++cnt; step[nq]=step[p]+1;
    memcpy(ch[nq],ch[q],sizeof(ch[q]));
    fa[nq]=fa[q]; fa[q]=fa[np]=nq;
    while (ch[p][c]==q) ch[p][c]=nq,p=fa[p];
}
void calc()
{
    scanf("%s",st+1);
    p=1;int tmp=0;
    int l=strlen(st+1);
    for (int i=1;i<=l;i++) 
    {
        int c=st[i]-'a';
        if (ch[p][c]) p=ch[p][c],tmp++;
        else 
        {
            while (p && !ch[p][c]) p=fa[p];
            if (!p) tmp=0,p=1;
            else tmp=step[p]+1,p=ch[p][c];
        }
        ans+=sum[p]+(LL)(tmp-step[fa[p]])*(LL)r[p];
    }
}
int main()
{
    scanf("%s",st+1);
    last=cnt=1;
    int l=strlen(st+1);
    for (int i=1;i<=l;i++) insert(st[i]-'a');

    for (int i=1;i<=cnt;i++) c[step[i]]++;
    for (int i=1;i<=cnt;i++) c[i]+=c[i-1];
    for (int i=1;i<=cnt;i++) a[c[step[i]]--]=i;

    p=1;
    for (int i=1;i<=l;i++) 
    {
        p=ch[p][st[i]-'a'];
        r[p]++;
    }
    for (int i=cnt;i;i--) r[fa[a[i]]]+=r[a[i]];
    for (int i=1;i<=cnt;i++) sum[a[i]]=sum[fa[a[i]]]+(LL)(step[fa[a[i]]]-step[fa[fa[a[i]]]])*(LL)r[fa[a[i]]];
    calc();
    printf("%lld",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值