前言
一、题目
题目链接: poj3261
二、思路与代码
1.思路
年轻人AC的第一道SA题目
学了一个星期的后缀数组和后缀自动机,做出的第一道SA题,感动
这道题目挺典型的
建立SA、Height数组,然后对Height进行二分
2.代码
代码如下:
#include <cstdio>
#include <iostream>
using namespace std;
const int maxn = 1e5 + 4;
const int inf = 0x3f3f3f3f;
int n, m, kk;
int s[maxn];
int sa[maxn], rk[maxn], height[maxn];
int sa2[maxn], oldrk[maxn], tank[maxn * 10];
bool cmp(int x, int y, int w) {
return oldrk[x] == oldrk[y] && oldrk[x + w] == oldrk[y + w];
}
void rsort() {
for (int i = 1; i <= m; i++) tank[i] = 0;
for (int i = 1; i <= n; i++) tank[rk[i]]++;
for (int i = 2; i <= m; i++) tank[i] += tank[i - 1];
for (int i = n; i >= 1; i--) sa[tank[rk[sa2[i]]]--] = sa2[i];
}
void getSA() {
m = maxn - 1;
for (int i = 1; i <= n; i++) rk[i] = s[i], sa2[i] = i;
rsort();
for (int k = 1; k <= n; k <<= 1) {
int cnt = 0;
for (int i = n - k + 1; i <= n; i++) sa2[++cnt] = i;
for (int i = 1; i <= n; i++)
if (sa[i] > k) sa2[++cnt] = sa[i] - k;
rsort();
swap(rk, oldrk);
cnt = 1;
rk[sa[1]] = 1;
for (int i = 2; i <= n; i++) {
rk[sa[i]] = cmp(sa[i], sa[i - 1], k) ? cnt : ++cnt;
}
m = cnt;
}
}
void getHi() {
int k = 0;
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;
}
}
bool judge(int len) {
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (height[i] < len) {
cnt = 0;
} else {
cnt++;
}
if (cnt >= kk - 1) return true;
}
return false;
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d%d", &n, &kk);
int x, mx;
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
s[i] = x + 1;
mx = max(mx, s[i]);
}
getSA();
getHi();
int l = 0, r = n;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (judge(mid)) {
l = mid;
} else {
r = mid - 1;
}
}
printf("%d\n", l);
return 0;
}