pku1743Musical Theme 后缀数组+二分

二分很强大,大神题解 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<bitset>
#define LL long long
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define down(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
inline LL read()
{
	LL d=0,f=1;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
	return d*f;
}
#define N 20005
int sa[N],ra[N],height[N],a[N],b[N];
int n,m;

int c[N];
void getsa(int m)
{
	memset(sa,0,sizeof(sa));
	memset(ra,0,sizeof(ra));
	memset(height,0,sizeof(height));
	fo(i,0,m)c[i]=0;
	fo(i,1,n)ra[i]=b[i],c[b[i]]++;
	fo(i,1,m)c[i]+=c[i-1];
	down(i,n,1)sa[c[ra[i]]--]=i;
	for(int k=1;k<=n;k<<=1)
	{
		int p=0;
		fo(i,n-k+1,n)height[++p]=i;
		fo(i,1,n)if(sa[i]>k)height[++p]=sa[i]-k;
		fo(i,0,m)c[i]=0;
		fo(i,1,n)c[ra[height[i]]]++;
		fo(i,1,m)c[i]+=c[i-1];
		down(i,n,1)sa[c[ra[height[i]]]--]=height[i];
		swap(ra,height);p=0;ra[sa[1]]=++p;
		fo(i,2,n)
		if(height[sa[i]]==height[sa[i-1]]&&height[sa[i]+k]==height[sa[i-1]+k])
		ra[sa[i]]=p;else ra[sa[i]]=++p;
		if(p==n)break;m=p;
	}
//	cout<<"SA:";fo(i,1,n)cout<<sa[i]<<' ';cout<<endl;
}

void getheight()
{
	memset(height,0,sizeof(height));
	int j=0,k=0;
	for(int i=1;i<=n;height[ra[i++]]=k)
	for(k?k--:0,j=sa[ra[i]-1];b[i+k]==b[j+k];k++);
//	cout<<"HEIGHT:";fo(i,1,n)cout<<height[i]<<' ';cout<<endl;
}	

bool check(int x)
{
	int mi=sa[1],ma=sa[1];
//	cout<<"CHECK"<<x<<endl;
	fo(i,2,n)
	{
		if(height[i]<x)mi=sa[i],ma=sa[i];
		else
		{
			mi=min(mi,sa[i]);
			ma=max(ma,sa[i]);
			if(ma-mi>=x)return 1;
		}
//		cout<<mi<<' '<<ma<<endl;
	}
	return 0;
}

int main()
{
	while(scanf("%d",&n),n)
	{
		if(n<=5)
		{
			int x;
			fo(i,1,n)scanf("%d",&x);
			printf("0\n");
			continue;
		}
		fo(i,1,n)scanf("%d",&a[i]);b[n]=0;
		fo(i,1,n-1)b[i]=a[i+1]-a[i]+89;n--;
		getsa(181);
		getheight();
		int l=0,r=n/2,ans=0;
		while(l<=r)
		{
			int mid=(l+r)>>1;
			if(check(mid))
			{
				l=mid+1;
				ans=mid;
			}else r=mid-1;
		}
		if(ans>=4)printf("%d\n",ans+1);else printf("0\n");
	}
	return 0;
}


你可能感兴趣的:(pku1743Musical Theme 后缀数组+二分)