Bzoj4566:[HAOI2016]找相同字符

Posted Cyhlnj

tags:

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

题面

Bzoj

Sol

两个串拼在一起后求出后缀数组
然后显然的\(n^2\)暴力,就是直接枚举求\(LCP\)
又由于扫的时候是对\(height\)\(min\)
那么可以用单调栈维护每一段的贡献相同的

# 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 _(4e5 + 5);

int n, a[_], is[_], rk[_], sa[_], height[_], tmp[_], t[_];
int S[_], top, s1[_], s2[_];
ll ans, sum[_];
char ss[_];

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

IL void Suffix_Sort(){
    RG int m = 27;
    for(RG int i = 1; i <= n; ++i) ++t[rk[i] = a[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 = 0; 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(a[i + h] == a[sa[rk[i] - 1] + h]) ++h;
        height[rk[i]] = h;
    }
}

int main(RG int argc, RG char* argv[]){
    scanf(" %s", ss);
    for(RG int i = 0, len = strlen(ss); i < len; ++i) a[++n] = ss[i] - 'a' + 1, is[n] = 1;
    scanf(" %s", ss), a[++n] = 27;
    for(RG int i = 0, len = strlen(ss); i < len; ++i) a[++n] = ss[i] - 'a' + 1, is[n] = 2;
    Suffix_Sort();
    for(RG int i = 1; i < n; ++i)
        s1[i] = s1[i - 1] + (is[sa[i]] == 1), s2[i] = s2[i - 1] + (is[sa[i]] == 2);
    S[0] = 1;
    for(RG int i = 1; i < n; ++i){
        while(top && height[S[top]] > height[i]) --top;
        S[++top] = i, sum[top] = sum[top - 1] + (s1[i - 1] - s1[S[top - 1] - 1]) * height[i];
        if(is[sa[i]] == 2) ans += sum[top];
    }
    top = 0;
    for(RG int i = 1; i < n; ++i){
        while(top && height[S[top]] > height[i]) --top;
        S[++top] = i, sum[top] = sum[top - 1] + (s2[i - 1] - s2[S[top - 1] - 1]) * height[i];
        if(is[sa[i]] == 1) ans += sum[top];
    }
    printf("%lld\n", ans);
    return 0;
}

以上是关于Bzoj4566:[HAOI2016]找相同字符的主要内容,如果未能解决你的问题,请参考以下文章

bzoj 4566 [Haoi2016]找相同字符SA

bzoj4566: [Haoi2016]找相同字符

●BZOJ 4566 [Haoi2016]找相同字符

Bzoj4566 [Haoi2016]找相同字符

Bzoj4566 [Haoi2016]找相同字符

BZOJ4566:[HAOI2016]找相同字符——题解