先求后缀数组,再二分答案。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define Rep(i, x, y) for (int i = x; i <= y; i ++)
#define RepE(i, x) for (int i = pos[x]; i; i = g[i].nex)
#define Dwn(i, x, y) for (int i = x; i >= y; i --)
using namespace std;
typedef long long LL;
const int N = 20005, M = 1000005;
int n, a[N], sa[N], ht[N], c[M], t1[N], t2[N], rk[N], m;
bool Cmp(int *r, int x, int y, int l) { return r[x] == r[y] && r[x+l] == r[y+l]; }
void Bsa(int *a, int n, int m) {
int *x = t1, *y = t2, p = 0;
Rep(i, 0, m) c[i] = 0;
Rep(i, 0, n) c[x[i] = a[i]] ++;
Rep(i, 1, m) c[i] += c[i-1];
Rep(i, 0, n) sa[-- c[ x[i] ]] = i;
for (int j = 1; p <= n; j <<= 1, m = p) {
p = 0;
Rep(i, n-j+1, n) y[p ++] = i;
Rep(i, 0, n) if (sa[i] >= j) y[p ++] = sa[i] - j;
Rep(i, 0, m) c[i] = 0;
Rep(i, 0, n) c[ x[y[i]] ] ++;
Rep(i, 1, m) c[i] += c[i-1];
Dwn(i, n, 0) sa[-- c[ x[y[i]] ]] = y[i];
swap(x, y), p = 1, x[ sa[0] ] = 0;
Rep(i, 1, n) x[ sa[i] ] = Cmp(y, sa[i], sa[i-1], j) ? p - 1 : p ++;
}
}
void Bh(int *a, int n) {
Rep(i, 0, n) rk[ sa[i] ] = i;
int k = 0;
Rep(i, 0, n-1) {
if (k) k --;
int j = sa[ rk[i] - 1 ];
while (a[i+k] == a[j+k]) k ++;
ht[ rk[i] ] = k;
}
}
int main()
{
scanf ("%d%d", &n, &m), m --;
Rep(i, 0, n-1) scanf ("%d", &a[i]), a[i] ++;
Bsa(a, n, M-2), Bh(a, n);
int l = 0, r = n;
while (l < r) {
int mid = (l + r + 1) >> 1, o = 0, f = 0;
Rep(i, 2, n) {
if (ht[i] >= mid) o ++;
else o = 0;
if (o >= m) { f = 1; break; }
}
if (f) l = mid;
else r = mid - 1;
}
printf ("%d\n", l);
return 0;
}