题目链接:http://poj.org/problem?id=1743
题意:给你N个数,相邻两数相减可以得到一段长为N-1的数列,可以当作字符串,现在让你找出最长重复子串长度,且这两个子串不能有重叠部分,如果该长度 < 4,输出0
思路:通过二分答案判定是否存在两个长度为k的子串是相同的,且不重叠。利用height数组将排序后的后缀分组,每组后缀间的height都 >= k,故而最长lcp不小于k的两个后缀一定在同一组,对于每组后缀,维护他们sa的最大值和最小值,如果这两值之差即位置相隔 >= k,则可行
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <utility>
#include <functional>
#include <algorithm>
#include <string>
#include <queue>
#include <cctype>
#include <set>
#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int MAXN = 20010;
int t1[MAXN], t2[MAXN], c[MAXN];
bool cmp(int *r, int a, int b, int l)
{
return r[a] == r[b] && r[a + l] == r[b + l];
}
void da(int str[], int sa[], int rank[], int height[], int n, int m)
{
n++;
int i, j, p, *x = t1, *y = t2;
for (i = 0; i < m; i++) c[i] = 0;
for (i = 0; i < n; i++) c[x[i] = str[i]]++;
for (i = 1; i < m; i++) c[i] += c[i - 1];
for (i = n - 1; i >= 0; i--) sa[--c[x[i]]] = i;
for (j = 1; j <= n; j <<= 1)
{
p = 0;
for (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 < 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];
swap(x, y);
p = 1; x[sa[0]] = 0;
for (i = 1; i < n; i++)
x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++;
if (p >= n)break;
m = p;
}
int k = 0;
n--;
for (i = 0; i <= n; i++) rank[sa[i]] = i;
for (i = 0; i < n; i++)
{
if (k) k--;
j = sa[rank[i] - 1];
while (str[i + k] == str[j + k]) k++;
height[rank[i]] = k;
}
}
int rank[MAXN], height[MAXN];
int r[MAXN], sa[MAXN];
bool ok(int mid, int n)
{
int ma = sa[1], mi = sa[1];
for (int i = 2; i <= n; i++)
{
if (height[i] < mid) ma = mi = sa[i];
else
{
ma = max(ma, sa[i]);
mi = min(mi, sa[i]);
if (ma - mi >= mid)
return true;
}
}
return false;
}
int main()
{
int n;
while (~scanf("%d", &n) && n)
{
for (int i = 0; i < n; i++)
scanf("%d", &r[i]);
for (int i = 0; i < n - 1; i++)
{
r[i] = r[i + 1] - r[i] + 100;
}
n--;
r[n] = 0;
da(r, sa, rank, height, n, 256);
int l = 0, r = n, ans = 0;
while (l <= r)
{
int mid = (l + r) >> 1;
if (ok(mid, n))
{
if (ans < mid)
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
if (ans < 4)
puts("0");
else
printf("%d\n", ans + 1);
}
return 0;
}