洛谷 P4248 [AHOI2013]差异 后缀自动机

题目描述

给定一个长度为 n n 的字符串S,令 Ti T i 表示它从第 i i 个字符开始的后缀。求

i=1n1j=i+1nlen(Ti)+len(Tj)2lcp(Ti,Tj)

其中, len(a) l e n ( a ) 表示字符串 a a 的长度,lcp(a,b)表示字符串 a a 和字符串b的最长公共前缀。

输入输出格式

输入格式:
一行,一个字符串 S S

输出格式:
一行,一个整数,表示所求值。

输入输出样例

输入样例#1:
cacao
输出样例#1:
54
说明
对于 100% 的数据,保证 2n500000 ,且均为小写字母。

分析:
主要就是求每两个子串的 lcp l c p
两个串 lcp l c p 的长度就是 fail f a i l 树上的 lca l c a
这个东西还没搞懂,所以就不解释了。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define LL long long

const int maxn=1e6+7;

using namespace std;

int n,cnt,size[maxn],b[maxn],top[maxn],sum[maxn];
char s[maxn];
LL ans;

struct node{
    int len,fail;
    int son[26];
}t[maxn];

void build_sam()
{
    cnt=1;
    int now=1,p,q,clone;
    for (int i=0;i<n;i++)
    {
        int c=s[i]-'a';
        p=now;
        now=++cnt;
        t[now].len=t[p].len+1;
        size[now]=sum[now]=1;
        while (p&&(!t[p].son[c])) t[p].son[c]=now,p=t[p].fail;
        if (!p) t[now].fail=1;
        else
        {
            q=t[p].son[c];
            if (t[p].len+1==t[q].len) t[now].fail=q;
            else
            {               
                clone=++cnt;
                t[clone]=t[q];
                t[clone].len=t[p].len+1;
                t[q].fail=t[now].fail=clone;
                while (p&&(t[p].son[c]==q)) t[p].son[c]=clone,p=t[p].fail;
            }
        }
    }
}

void calc()
{
    for (int i=1;i<=cnt;i++) b[t[i].len]++;
    for (int i=1;i<=n;i++) b[i]+=b[i-1];
    for (int i=1;i<=cnt;i++) top[b[t[i].len]--]=i;  
    for (int i=cnt;i>0;i--) 
      size[t[top[i]].fail]+=size[top[i]];
    ans=0;  
    for (int i=1;i<=n;i++) ans+=(LL)i*(n-1);    
    for (int i=cnt;i>0;i--)
    {
        ans-=(LL)sum[t[i].fail]*size[i]*t[t[i].fail].len*2;
        sum[t[i].fail]+=size[i];
    } 
    printf("%lld",ans);
}

int main()
{
    scanf("%s",s);
    n=strlen(s);
    build_sam();
    calc();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值