1. 程式人生 > >【AHOI2013】—差異(字尾自動機)

【AHOI2013】—差異(字尾自動機)

傳送門

大意:給你一個字串,求所有子串兩兩的最長公共字首之和

考慮我們可以把串倒過來建 S a m Sam ,就變成了求所有子串的最長公共字尾之和

就是 P a

r e n t T r e e Parent-Tree
上兩個 e n d p o s endpos 集合的距離

看到一種妙♂妙的方法

直接考慮每條邊 e

e 對答案的貢獻

就是其 s i z [ e ] ( n s i z [ e ] ) ( e n d p o s ) ( s i z ) siz[e]*(n-siz[e])*(endpos集合大小)(siz是子樹大小)

列舉每個點考慮一下他和他父親就可以了

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){
    char ch=getchar();
    int res=0;
    while(!isdigit(ch))ch=getchar();
    while(isdigit(ch))res=(res<<3)+(res<<1)+(ch^48);
    return res;
}
const int N=500005;
int tot,last;
long long ans;
int c[N<<1],p[N<<1],len[N<<1],link[N<<1],nxt[N<<1][27],cnt[N<<1];
char a[N];
inline int extend(int c){
    int cur=++tot,p=last;last=cur;
    len[cur]=len[p]+1,cnt[cur]=1;
    for(;p&&!nxt[p][c];p=link[p])nxt[p][c]=cur;
    if(!p)link[cur]=1;
    else{
        int q=nxt[p][c];
        if(len[p]+1==len[q])link[cur]=q;
        else{
            int clo=++tot;
            for(int i=0;i<=26;i++)nxt[clo][i]=nxt[q][i];
            link[clo]=link[q],len[clo]=len[p]+1;
            for(;p&&nxt[p][c]==q;p=link[p])nxt[p][c]=clo;
            link[q]=link[cur]=clo;
        }
    }
}
signed main(){
    scanf("%s",a+1),last=tot=1;
    int lenth=strlen(a+1);
    for(int i=lenth;i>=1;i--)extend(a[i]-'a');
    for(int i=1;i<=tot;i++)c[len[i]]++;
    for(int i=1;i<=tot;i++)c[i]+=c[i-1];
    for(int i=1;i<=tot;i++)p[c[len[i]]--]=i;
    for(int i=tot;i>=1;i--){
        cnt[link[p[i]]]+=cnt[p[i]];
        ans+=(len[p[i]]-len[link[p[i]]])*(cnt[p[i]])*(lenth-cnt[p[i]]);
    }
    cout<<ans;
}