Bzoj3238: [Ahoi2013]差异

Posted Cyhlnj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bzoj3238: [Ahoi2013]差异相关的知识,希望对你有一定的参考价值。

题面

Bzoj

Sol

刚完品酒大会那道题后再看这道题发现这就是道\(SB\)
后缀数组+并查集
\(height\)从大到小做
\(height\)是两个相邻\(rank\)的后缀的\(LCP\)
从大到小,那么每次合并\(height\)的两边的集合,同时记录答案
两边集合两两配对的\(LCP\)一定就是这个\(height\),乘法原理就可以了
这也算是一种套路吧


代码我常数大我最菜

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(5e5 + 5);

IL int Input(){
    RG int x = 0, z = 1; RG char c = getchar();
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

int n, s[_], sa[_], rk[_], tmp[_], t[_], height[_], id[_];
int fa[_], size[_];
ll ans;
char ss[_];

IL int Find(RG int x){
    return x == fa[x] ? x : fa[x] = Find(fa[x]);
}

IL ll S(RG ll x){
    return x * (x + 1) / 2;
}

IL int Cmp(RG int i, RG int j, RG int k){
    return tmp[i] == tmp[j] && i + k <= n && j + k <= n && tmp[i + k] == tmp[j + k];
}

IL void Suffix_Sort(){
    RG int m = 26;
    for(RG int i = 1; i <= n; ++i) ++t[rk[i] = s[i]];
    for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
    for(RG int i = n; i; --i) sa[t[rk[i]]--] = i;
    for(RG int k = 1; k <= n; k <<= 1){
        RG int l = 0;
        for(RG int i = n - k + 1; i <= n; ++i) tmp[++l] = i;
        for(RG int i = 1; i <= n; ++i) if(sa[i] > k) tmp[++l] = sa[i] - k;
        for(RG int i = 1; i <= m; ++i) t[i] = 0;
        for(RG int i = 1; i <= n; ++i) ++t[rk[tmp[i]]];
        for(RG int i = 1; i <= m; ++i) t[i] += t[i - 1];
        for(RG int i = n; i; --i) sa[t[rk[tmp[i]]]--] = tmp[i];
        swap(rk, tmp), rk[sa[1]] = l = 1;
        for(RG int i = 2; i <= n; ++i) rk[sa[i]] = Cmp(sa[i - 1], sa[i], k) ? l : ++l;
        if(l >= n) break;
        m = l;
    }
    for(RG int i = 1, h = 0; i <= n; ++i){
        if(h) --h;
        while(s[i + h] == s[sa[rk[i] - 1] + h]) ++h;
        height[rk[i]] = h;
    }
}

IL int _Cmp(RG int x, RG int y){
    return height[x] > height[y];
}

int main(RG int argc, RG char* argv[]){
    scanf(" %s", ss + 1), n = strlen(ss + 1);
    for(RG int i = 1; i <= n; ++i){
        s[i] = ss[i] - 'a' + 1, id[i] = fa[i] = i, size[i] = 1;
        ans += S(n - i) + 1LL * (n - i) * (n - i + 1);
    }
    Suffix_Sort(), sort(id + 2, id + n + 1, _Cmp);
    for(RG int i = 2; i <= n; ++i){
        RG int x = Find(sa[id[i] - 1]), y = Find(sa[id[i]]);
        ans -= 2LL * size[x] * size[y] * height[id[i]];
        fa[x] = y, size[y] += size[x];
    }
    printf("%lld\n", ans);
    return 0;
}

以上是关于Bzoj3238: [Ahoi2013]差异的主要内容,如果未能解决你的问题,请参考以下文章

Bzoj3238: [Ahoi2013]差异

bzoj 3238: [Ahoi2013]差异 -- 后缀数组

bzoj3238 [Ahoi2013]差异

bzoj3238 [Ahoi2013]差异 后缀数组+单调栈

bzoj 3238: [AHOI2013]差异

BZOJ_3238_[Ahoi2013]差异_后缀自动机