【POJ 1743】Musical Theme

时间:2023-11-28 10:11:02

后缀数组求了height,模板题啦啦啦

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 21003; int t1[N], t2[N], c[N];
void st(int *x, int *y, int *sa, int n, int m) {
int i;
for(i = 0; i < m; ++i) c[i] = 0;
for(i = 0; i < n; ++i) ++c[x[y[i]]];
for(i = 1; i < m; ++i) c[i] += c[i - 1];
for(i = n - 1; i >= 0; --i) sa[--c[x[y[i]]]] = y[i];
}
void mkhz(int *r, int *sa, int n, int m) {
int *x, *y, *t, j, i, p;
x = t1; y = t2;
for(i = 0; i < n; ++i) x[i] = r[i], y[i] = i;
st(x, y, sa, n, m);
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;
st(x, y, sa, n, m);
for(t = x, x = y, y = t, x[sa[0]] = 0, p = 1, i = 1; i < n; ++i)
x[sa[i]] = y[sa[i]] == y[sa[i - 1]] && y[sa[i] + j] == y[sa[i - 1] + j] ? p - 1 : p++;
}
}
void mkh(int *a, int *sa, int *rank, int *h, int n) {
int k = 0, i, j;
for(i = 1; i <= n; ++i) rank[sa[i]] = i;
for(i = 1; i <= n; h[rank[i++]] = k)
for(k ? k-- : 0, j = sa[rank[i] - 1]; a[i + k] == a[j + k]; ++k);
} int sa[N], rank[N], h[N], a[N], n;
bool can(int k) {
int minnum = sa[1], maxnum = sa[1];
for(int i = 2; i <= n; ++i)
if (h[i] >= k) {
minnum = min(minnum, sa[i]);
maxnum = max(maxnum, sa[i]);
if (maxnum - minnum >= k)
return 1;
} else minnum = sa[i], maxnum = sa[i];
return 0;
} int main() {
while (scanf("%d", &n), n) {
scanf("%d", &a[1]);
--n;
for(int i = 1; i <= n; ++i) scanf("%d", &a[i + 1]), a[i] = a[i + 1] - a[i] + 100;
mkhz(a, sa, n + 1, 200);
mkh(a, sa, rank, h, n);
int left = 0, right = n / 2, mid;
while (left <= right) {
mid = (left + right) >> 1;
if (can(mid)) left = mid + 1;
else right = mid - 1;
}
printf("%d\n", left >= 5 ? left : 0);
}
return 0;
}

我好弱啊