码迷,mamicode.com
首页 > 其他好文 > 详细

Bzoj3238: [Ahoi2013]差异

时间:2018-02-22 19:55:07      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:==   span   down   register   char   logs   wap   online   input   

题面

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]差异

标签:==   span   down   register   char   logs   wap   online   input   

原文地址:https://www.cnblogs.com/cjoieryl/p/8459491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!