二分+height分组

height分组真的很常用。我们只要二分长度就可以了。
值得注意的是,第一次满足长度的height[i]此是贡献的相等的为2个后缀

代码如下

#include<iostream>
#include<algorithm>
#include<map>
#include<cstdio>
using namespace std;
const int max_n = 2e4 + 100;

int a[max_n];
int ranks[max_n], SA[max_n], height[max_n];
int wa[max_n], wb[max_n], wvarr[max_n], wsarr[max_n];
inline int cmp(int* r, int a, int b, int l) {
    return r[a] == r[b] && r[a + l] == r[b + l];
}
inline void get_sa(int* r, int* sa, int n, int m) {
    //r:原数组
    //sa:SA
    //n:原数组长度
    //m:原数组种类数,用于基数排序
    ++n;
    int i, j, p, * x = wa, * y = wb, * t;
    for (i = 0; i < m; ++i) wsarr[i] = 0;
    for (i = 0; i < n; ++i) wsarr[x[i] = r[i]]++;
    for (i = 1; i < m; ++i) wsarr[i] += wsarr[i - 1];
    for (i = n - 1; i >= 0; --i) sa[--wsarr[x[i]]] = i;
    for (j = 1, p = 1; p < n; j <<= 1, m = p) {
        for (p = 0, i = n - j; i < n; ++i) y[p++] = i;
        for (i = 0; i < n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j;
        for (i = 0; i < n; ++i) wvarr[i] = x[y[i]];
        for (i = 0; i < m; ++i) wsarr[i] = 0;
        for (i = 0; i < n; ++i) wsarr[wvarr[i]]++;
        for (i = 1; i < m; ++i) wsarr[i] += wsarr[i - 1];
        for (i = n - 1; i >= 0; --i) sa[--wsarr[wvarr[i]]] = y[i];
        for (t = x, x = y, y = t, p = 1, x[sa[0]] = 0, i = 1; i < n; ++i)
            x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++;
    }
}//求解高度数组,height[i]指排名
void get_height(int* r, int* sa, int n) {
    int i, j, k = 0;
    for (i = 1; i <= n; ++i) ranks[sa[i]] = i;
    for (i = 0; i < n; height[ranks[i++]] = k)
        for (k ? k-- : 0, j = sa[ranks[i] - 1]; r[i + k] == r[j + k]; k++);
    return;
}

int N, K;
int b[max_n];

bool check(int mid) {
    int cnt = 1;
    for (int i = 1;i <= N;++i) {
        if (height[i] >= mid)++cnt;
        else cnt = 1;
        if (cnt >= K)return true;
    }return false;
}
int binary() {
    int lft = 0;int rght = N + 1;
    while (lft < rght) {
        int mid = (lft + rght) >> 1;
        if (check(mid))lft = mid + 1;
        else rght = mid;
    }return rght - 1;
}
int main() {
    scanf("%d %d", &N, &K);
    for (int i = 0;i < N;++i)scanf("%d", &a[i]);
    for (int i = 0;i < N;++i)b[i] = a[i];
    sort(b, b + N);map<int, int> mp;int tot = 0;
    mp[b[0]] = ++tot;
    for (int i = 1;i < N;++i)
        if (b[i] != b[i - 1])
            mp[b[i]] = ++tot;
    for (int i = 0;i < N;++i)a[i] = mp[a[i]];
    get_sa(a, SA, N, N + 10);
    get_height(a, SA, N);
    printf("%d\n", binary());
}