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

Bzoj4566:[HAOI2016]找相同字符

时间:2018-02-21 22:17:00      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:zoj   namespace   std   直接   argv   mem   pos   ons   scanf   

题面

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]找相同字符

标签:zoj   namespace   std   直接   argv   mem   pos   ons   scanf   

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

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