代码如下:
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAXN = 22222; int s[MAXN]; int sa[MAXN],rank[MAXN],height[MAXN]; int t[MAXN],t2[MAXN],c[MAXN]; void get_height(int n) { for(int i = 1;i <= n;i++) rank[sa[i]] = i; int k = 0; for(int i = 0;i < n;i++) { if(k) k--; int j = sa[rank[i]-1]; while( s[i+k] == s[j+k]) k++; height[rank[i]] = k; } } void da(int n,int m) { int *x = t,*y = t2; for(int i = 0;i < m;i++) c[i] = 0; for(int i = 0;i < n;i++) c[x[i] = s[i]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[i]]] = i; for(int k = 1;k <= n;k <<= 1) { int p = 0; for(int i = n-k;i < n;i++) y[p++] = i; for(int i = 0;i < n;i++) if(sa[i] >= k) y[p++] = sa[i]-k; for(int i = 0;i < m;i++) c[i] = 0; for(int i = 0;i < n;i++) c[x[y[i]]]++; for(int i = 1;i < m;i++) c[i] += c[i-1]; for(int i = n-1;i >= 0;i--) sa[--c[x[y[i]]]] = y[i]; swap(x,y); p = 1; x[sa[0]] = 0; for(int i = 1;i < n;i++) x[sa[i]] = y[sa[i]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k] ? p-1 : p++; if(p >= n) break; m = p; } //for(int i = 0;i < n;i++) //printf("i = %d,sa = %d\n",i,sa[i]); get_height(n-1); } int is_over(int a,int b,int mid) { if(a+mid-1 < b-1) return 0; else return 1; } int check(int mid,int n) { int max_pos = sa[1],min_pos = sa[1]; for(int i = 2;i <= n;i++) { if(height[i] < mid) { if(!is_over(min_pos,max_pos,mid)) return 1; max_pos = min_pos = sa[i]; } else { max_pos = max(max_pos,sa[i]); min_pos = min(min_pos,sa[i]); } } if(!is_over(min_pos,max_pos,mid)) return 1; return 0; } int solve(int n) { int l = 1,r = n; int ans = 0; while(l <= r) { int mid = (l+r) >> 1; //printf("l = %d,r = %d,mid = %d\n",l,r,mid); if(check(mid,n)) { ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } int num[MAXN]; int main() { int n; while(~scanf("%d",&n) && n) { for(int i = 0;i < n;i++) scanf("%d",&num[i]); for(int i = 1;i < n;i++) s[i-1] = num[i]-num[i-1]+88; s[n-1] = 0; //for(int i = 0;i < n;i++) //printf("i = %d,si = %d\n",i,s[i]); da(n,88+88); int ans = solve(n-1)+1; //printf("ans = %d\n",ans); if(ans >= 5) printf("%d\n",ans); else puts("0"); } return 0; } /* 10 1 1 1 1 1 1 1 1 1 1 9 1 1 1 1 1 1 1 1 1 */