[BZOJ]3238 差异 后缀树

3238: [Ahoi2013]差异

Time Limit: 20 Sec   Memory Limit: 512 MB
Submit: 3905   Solved: 1762
[ Submit][ Status][ Discuss]

Description

Input

一行,一个字符串S

Output

 

一行,一个整数,表示所求值

Sample Input

cacao

Sample Output


54

HINT



2<=N<=500000,S由小写英文字母组成

Source

[ Submit][ Status][ Discuss]


HOME Back

  今天顺便看了下后缀树是什么玩意儿... 明白了原来就是反串的parent树?

  这道题对反串建后缀自动机, 求出后缀树后, 两个后缀在后缀树上的lca的长度就是lcp, 那么dfs一遍就知道每个点被贡献了多少次... 就可以统计答案了.

  其实没必要dfs直接基数排序一下就好了.

#include
using namespace std;
const int maxn = 5e5 + 5;
int n;
char ss[maxn];
struct Suffix_Automaton {
    long long ans;
    int tot, last, root;
    int cnt[maxn], sa[maxn << 1];
    int siz[maxn << 1], c[maxn << 1][26], par[maxn << 1], len[maxn << 1];
    inline void init() {
        tot = 0;
        root = last = ++ tot;
    }
    inline void insert(int idx) {
        int p = last, np = last = ++ tot;
        len[np] = len[p] + 1, siz[np] = 1;
        while (p && !c[p][idx]) c[p][idx] = np, p = par[p];
        if (!p) par[np] = root;
        else {
            int q = c[p][idx];
            if (len[q] == len[p] + 1) par[np] = q;
            else {
                int nq = ++ tot;
                len[nq] = len[p] + 1, par[nq] = par[q];
                memcpy(c[nq], c[q], sizeof(c[q]));
                par[np] = par[q] = nq;
                while (c[p][idx] == q) c[p][idx] = nq, p = par[p];
            }
        }
    }
    inline void Radix_sort() {
        for (register int i = 1; i <= tot; ++ i) cnt[len[i]] ++;
        for (register int i = 1; i <= n; ++ i) cnt[i] += cnt[i - 1];
        for (register int i = 1; i <= tot; ++ i) sa[cnt[len[i]] --] = i; 
    }
    inline long long solve() {
        Radix_sort();
        for (register int i = tot; i > 1; -- i) {
            int nw = sa[i];
            ans += 1ll * len[par[nw]] * siz[par[nw]] * siz[nw];
            siz[par[nw]] += siz[nw];
        }
        return ans << 1;
    }
}sam;
int main() {
    scanf("%s", ss);
    n = strlen(ss);
    sam.init();
    for (register int i = n - 1; ~i; -- i) sam.insert(ss[i] - 'a');
    printf("%lld\n", (1ll * n * (n + 1) * (n - 1) >> 1) - sam.solve());
    return 0;
}

你可能感兴趣的:(BZOJ)