题目链接:http://poj.org/problem?id=1743
题意:求序列中最长不重叠重复字串
二分答案
#include <cstdio>
#include <cstring>
//#include <iostream>
#include <algorithm>
#include <vector>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 20000 + 5;
int wa[maxn],wb[maxn],wv[maxn],ws[maxn];
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 *sa,int n,int m)
{
int i,j,p,*x=wa,*y=wb,*t;
for(i=0;i<m;i++) ws[i]=0;
for(i=0;i<n;i++) ws[x[i]=r[i]]++;
for(i=1;i<m;i++) ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--) sa[--ws[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++) ws[i]=0;
for(i=0;i<n;i++) ws[wv[i]]++;
for(i=1;i<m;i++) ws[i]+=ws[i-1];
for(i=n-1;i>=0;i--) sa[--ws[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++;
}
return;
}
int rank[maxn],height[maxn];
void calheight(int *r,int *sa,int n)
{
int i,j,k=0;
for(i=1;i<=n;i++) rank[sa[i]]=i;
for(i=0;i<n;height[rank[i++]]=k)
for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);
return;
}
int sa[maxn];
int num[maxn];
vector<int> S[maxn];
bool check(int k,int n){
int cur = 0;
for(int i = 1;i <= n - 1;++i){
if(height[i] < k) S[++cur].clear();
S[cur].push_back(i);
}
for(int i = 0;i <= cur;++i){
int MIN_POS = n + 50,MAX_POS = -1;
for(int j = 0;j < S[i].size();++j){
MIN_POS = min(MIN_POS,sa[S[i][j]]);
MAX_POS = max(MAX_POS,sa[S[i][j]]);
if(MIN_POS + k <= MAX_POS) return true;
}
}
return false;
}
int main(){
int n;
while( sf("%d",&n) && n ){
for(int i = 0;i < n;++i){
sf("%d",&num[i]);
}
for(int i = 0;i < n - 1;++i){
num[i] = num[i + 1] - num[i] + 100;
}
num[n - 1] = 0;
da(num,sa,n,256);
calheight(num,sa,n - 1);
int ans,l = 0,r = n,m;
while(l + 1< r){
m = l + r >> 1;
if(check(m,n)){
l = m;
}
else r = m;
}
pf("%d\n",(l >= 4 ) ? l + 1 : 0);
}
return 0;
}