题意:给出一个长度为n的数字序列,问可重叠的最长重复子串出现至少K次的长度。
题解:二分出长度x,判断连续height[i] >= x的情况如果出现K-1次就可以判断这个长度是成立的。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20005;
int wa[N], wb[N], ws[N], wv[N], sa[N];
int rank[N], height[N], s[N], n, K;
int cmp(int* r, int a, int b, int l) {
return (r[a] == r[b]) && (r[a + l] == r[b + l]);
}
void DA(int *r, int *sa, int n, int m) {
int i, j, p, *x = wa, *y = wb, *t;
for (i = 0; i < m; i++) ws[i] = 0;
for (i = 0; i < n; i++) ws[x[i] = r[i]]++;
for (i = 1; i < m; i++) ws[i] += ws[i - 1];
for (i = n - 1; i >= 0; i--) sa[--ws[x[i]]] = i;
for (j = 1, p = 1; p < n; j *= 2, 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++) wv[i] = x[y[i]];
for (i = 0; i < m; i++) ws[i] = 0;
for (i = 0; i < n; i++) ws[wv[i]]++;
for (i = 0; i < m; i++) ws[i] += ws[i - 1];
for (i = n - 1; i >= 0; i--) sa[--ws[wv[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++;
}
}
void calheight(int *r, int *sa, int n) {
int i, j, k = 0;
for (i = 1; i <= n; i++) rank[sa[i]] = i;
for (i = 0; i < n; height[rank[i++]] = k)
for (k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; k++);
}
//sa[i]表示排第i的位置
//height[i]表示sa[i]与sa[i - 1]最长公共前缀
int judge(int x) {
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (height[i] >= x) {
cnt++;
if (cnt >= K - 1) return 1;
}
else cnt = 0;
}
return 0;
}
int main() {
while (scanf("%d%d", &n, &K) == 2) {
int maxx = 0;
for (int i = 0; i < n; i++) {
scanf("%d", &s[i]);
maxx = max(maxx, s[i]);
}
if (K <= 1) {
printf("%d\n", n);
continue;
}
s[n] = 0;
DA(s, sa, n + 1, maxx + 10);
calheight(s, sa, n);
int l = 1, r = n;
while (l < r) {
int mid = (l + r + 1) / 2;
if (judge(mid))
l = mid;
else
r = mid - 1;
}
printf("%d\n", l);
}
return 0;
}