bzoj3238: [Ahoi2013]差異

Description
這裏寫圖片描述

Input
一行,一個字符串S

Output
一行,一個整數,表示所求值

Sample Input
cacao

Sample Output
54

HINT
2<=N<=500000,S由小寫英文字母組成

簡單來說就是求原串中所有後綴兩兩最長公共前綴之和..

那麼只要把原串反過來做SAM,把原問題變成所有前綴兩兩最長公共後綴之和

然後就要用到2015集訓隊論文中的性質5

這裏寫圖片描述

那麼題解就是顯而易見的啊..

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#define LL long long
using namespace std;
const LL Maxn = 1000010;
LL F[Maxn], d[Maxn], ch[Maxn][26], tot, now, size[Maxn], lca[Maxn];
char s[Maxn]; LL len;
LL Rsort[Maxn], rk[Maxn];
LL copy ( LL p, LL c ){
    LL x = ++tot, y = ch[p][c];
    d[x] = d[p]+1;
    for ( LL i = 0; i < 26; i ++ ) ch[x][i] = ch[y][i];
    F[x] = F[y]; F[y] = x;
    while ( ~p && ch[p][c] == y ){ ch[p][c] = x; p = F[p]; }
    return x;
}
void add ( LL c ){
    LL p, o;
    if ( p = ch[now][c] ){
        if ( d[p] != d[now]+1 ) copy ( now, c );
        now = ch[now][c];
    }
    else {
        d[o=++tot] = d[now]+1; p = now; now = o;
        while ( ~p && !ch[p][c] ){ ch[p][c] = o; p = F[p]; }
        F[o] = ~p ? ( d[p]+1 == d[ch[p][c]] ? ch[p][c] : copy ( p, c ) ) : 0;
    }
}
int main (){
    LL i, j, k;
    scanf ( "%s", s+1 );
    len = strlen (s+1);
    F[0] = -1; tot = now = 0;
    for ( i = len; i >= 1; i -- ){ add (s[i]-'a'); size[now] = 1; }
    for ( i = 1; i <= tot; i ++ ) Rsort[d[i]] ++;
    for ( i = 1; i <= len; i ++ ) Rsort[i] += Rsort[i-1];
    for ( i = tot; i >= 1; i -- ) rk[Rsort[d[i]]--] = i;
    LL ans = 0;
    for ( i = tot; i >= 1; i -- ){
        lca[F[rk[i]]] += size[F[rk[i]]]*size[rk[i]];
        size[F[rk[i]]] += size[rk[i]];
        ans += lca[rk[i]]*d[rk[i]];
    }
    printf ( "%lld\n", (len-1)*len*(len+1)/2-2*ans );
    return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章