[AHOI2013]差异 后缀自动机_Parent树

本文深入解析了AHOI2013竞赛中差异后缀自动机的实现原理及代码细节,展示了如何通过构建差异后缀自动机解决字符串匹配问题,包括Parent树的构建与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[AHOI2013]差异 后缀自动机_Parent树

Code:

#include <cstdio>
#include <algorithm>
#include <cstring>
#define setIO(s) freopen(s".in","r",stdin)
#define maxn 1000000
#define N 30
#define ll long long
using namespace std;
int last=1,tot=1,n;
int ch[maxn][N],cnt[maxn],f[maxn],dis[maxn],rk[maxn];
ll C[maxn],ans;
char str[maxn];
struct Suffix_Automaton{
    void ins(int c){
        int p=last,np=++tot; last=np; dis[np]=dis[p]+1;
        while(p&&!ch[p][c])ch[p][c]=np,p=f[p];
        if(!p) f[np]=1;
        else{
            int q=ch[p][c],nq; 
            if(dis[q]==dis[p]+1) f[np]=q;
            else{
                nq=++tot;
                dis[nq]=dis[p]+1;
                memcpy(ch[nq],ch[q],sizeof(ch[q]));
                f[nq]=f[q],f[q]=f[np]=nq;
                while(p&&ch[p][c]==q) ch[p][c]=nq,p=f[p];
            }
        }
        cnt[last]=1;
    }
}sam;
int main(){
    //s//etIO("input");
    scanf("%s",str),n=strlen(str);
    for(int i=n-1;i>=0;--i) sam.ins(str[i]-'a');
    for(int i=1;i<=tot;++i) ++C[dis[i]];
    for(int i=1;i<=tot;++i) C[i]+=C[i-1]; 
    for(int i=1;i<=tot;++i) rk[C[dis[i]]--]=i; 
    for(int i = 1;i <= n; ++i) ans += (long long)i * (n - 1); 
    for(int i=tot;i>=1;--i){
        int p=rk[i];
        ans -= (long long)2 * dis[f[p]] * cnt[p] * cnt[f[p]]; 
        cnt[f[p]]+=cnt[p];  
    }
    printf("%lld",ans);
    return 0;
}

  

  

posted @ 2019-01-29 00:53 EM-LGH 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值