• CSL 的密码(后缀数组)


    CSL 的密码

    题目传送门

    解题思路

    后缀数组。对于每一个后缀(k)都有(n - k + 1)个前缀,把所有不和前一个(排序后的)公共且长度大于(m)的前缀个数加起来。

    代码如下

    #include <bits/stdc++.h>
    #define INF 0x3f3f3f3f
    using namespace std;
    typedef long long ll;
    
    const int N = 100005;
    
    int x[N], y[N], c[N], sa[N];
    char s[N];
    int n, m;
    
    void get_SA()
    {
        for(int i = 1; i <= m; i ++) c[i] = 0;
        for(int i = 1; i <= n; i ++) c[x[i] = s[i]] ++;
        for(int i = 1; i <= m; i ++) c[i] += c[i - 1];
        for(int i = n; i >= 1; i --) sa[c[x[i]] --] = i;
        for(int k = 1; k <= n; k <<= 1){
            int num = 0;
            for(int i = n - k + 1; i <= n; i ++) y[++num] = i;
            for(int i = 1; i <= n; i ++) if(sa[i] > k) y[++num] = sa[i] - k;
            for(int i = 1; i <= m; i ++) c[i] = 0;
            for(int i = 1; i <= n; i ++) c[x[i]] ++;
            for(int i = 1; i <= m; i ++) c[i] += c[i - 1];
            for(int i = n; i >= 1; i --) sa[c[x[y[i]]] --] = y[i], y[i] = 0;
            num = 1;
            swap(x, y);
            x[sa[1]] = num;
            for(int i = 2; i <= n; i ++){
                if(sa[i] + k <= n && sa[i - 1] + k <= n)
                    x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k])? num: ++num;
                else
                    x[sa[i]] = ++num;
            }
            if(num == n)
                break;
            m = num;
        }
    }
    
    int height[N], rk[N];
    
    void get_h()
    {
        int k = 0;
        for(int i = 1; i <= n; i ++) rk[sa[i]] = i;
        for(int i = 1; i <= n; i ++){
            if(rk[i] == 1) continue;
            if(k) --k;
            int j = sa[rk[i] - 1];
            while(i + k <= n && j + k <= n && s[i + k] == s[j + k]) ++k;
            height[rk[i]] = k;
        }
    }
    
    int main()
    {
        int len;
        scanf("%d%d", &n, &len);
        m = 'z';
        scanf("%s", s + 1);
        get_SA();
        get_h();
        ll ans = 0;
        for(int i = 1; i <= n; i ++){
            if(sa[i] > n - len + 1) continue;
            int num = n - sa[i] + 1 - len + 1;
            ans += num - max(0, height[i] - len + 1);
        }
        printf("%lld
    ", ans);
        return 0;
    }
    
    
  • 相关阅读:
    【noip2012】开车旅行
    【AC自动机】专题总结
    【noi2013】【bz3244】树的计数
    BZOJ1069: [SCOI2007]最大土地面积
    BZOJ1185: [HNOI2007]最小矩形覆盖
    BZOJ1047: [HAOI2007]理想的正方形
    BZOJ1801: [Ahoi2009]chess 中国象棋
    BZOJ1925: [Sdoi2010]地精部落
    BZOJ1057: [ZJOI2007]棋盘制作
    BZOJ1217: [HNOI2003]消防局的设立
  • 原文地址:https://www.cnblogs.com/whisperlzw/p/11420443.html
Copyright © 2020-2023  润新知