思路:先二分答案,判断是否存在两个长度为k的子串是相同的,且不重叠。之后把排好序的后缀按照后缀之间的height值都不小于k分为若干组。例如当字符串为“aabaaaab”时,k = 2,后缀分成了如下4组:
可以看出,有希望成为最小公共前缀不小于k的两个后缀一定在同一组。然后对于每组后缀,只需判断每个后缀的sa值的最大值和最小值之差是否大于等于k。如果有一组满足则存在。
/***********************************************
* Author: fisty
* Created Time: 2015-08-23 17:24:54
* File Name : A.cpp
* 不可重叠最长重复子串
*********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define lson l, m, k<<1
#define rson m+1, r, k<<1|1
#define MAX_N 20100
//数字型
int k;
int sa[MAX_N], rank[MAX_N], tmp[MAX_N+1];
int lcp[MAX_N];
int a[MAX_N];
int wa[MAX_N], wb[MAX_N], wv[MAX_N], wd[MAX_N];
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 n, int m){ // 倍增算法 r为待匹配数组 n为总长度 m为字符范围
int i, j, p, *x = wa, *y = wb, *t;
for(i = 0; i < m; i ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[x[i]=r[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[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 ++) wd[i] = 0;
for(i = 0; i < n; i ++) wd[wv[i]] ++;
for(i = 1; i < m; i ++) wd[i] += wd[i-1];
for(i = n-1; i >= 0; i --) sa[-- wd[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 n){ // 求height数组。
int i, j, p = 0;
for(i = 1; i <= n; i ++) rank[sa[i]] = i;
for(i = 0; i < n; lcp[rank[i ++]] = p){
for(p ? p -- : 0, j = sa[rank[i]-1]; r[i+p] == r[j+p]; p ++);
}
}
int n;
bool ok(int x){
for(int i = 2;i <= n; i++){
if(lcp[i] < x) continue;
for(int j = i-1; j >= 2; j--){
if(abs(sa[j] - sa[i]) >= x) return true;
if(lcp[j] < x) break;
}
}
return false;
}
int solve(){
da(a, n, 200);
calHeight(a, n-1);
int l = 3, r = n;
int ans = 0;
while(r - l >= 0){
int mid = (l + r) / 2;
if(ok(mid)){
ans = mid;
l = mid + 1;
}else r = mid - 1;
}
return ans;
}
int main(){
//freopen("in.cpp", "r", stdin);
//cin.tie(0);
//ios::sync_with_stdio(false);
while(~scanf("%d", &n)){
if(!n) break;
for(int i = 0;i < n; i++){
scanf("%d", &a[i]);
}
for(int i = 0; i < n-1; i++){
a[i] = a[i+1] - a[i] + 90;
}
a[n-1] = 0;
int ans = solve();
printf("%d\n", ans >= 4 ? ans+1 : 0);
}
return 0;
}