【poj1743】 Musical Theme

http://poj.org/problem?id=1743 (题目链接)

题意

  给出n个音符的乐谱,求其中不重叠的重复最长连续段,重复连续段的定义为两段音符起伏相同。

Solution

  论文题,相邻两个音符取差值,然后height分组二分答案即可。

代码

// poj1743
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<cstdio>
#include<cmath>
#include<set>
#define LL long long
#define inf 1<<30
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

const int maxn=20010;
int s[maxn],a[maxn],rank[maxn],height[maxn],sa[maxn];
int n;

namespace Suffix {
	int wa[maxn],wb[maxn],ww[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 *r,int *sa,int n,int m) {
		int i,j,p,*x=wa,*y=wb;
		for (i=0;i<=m;i++) ww[i]=0;
		for (i=1;i<=n;i++) ww[x[i]=r[i]]++;
		for (i=1;i<=m;i++) ww[i]+=ww[i-1];
		for (i=n;i>=1;i--) sa[ww[x[i]]--]=i;
		for (p=0,j=1;p<n;j*=2,m=p) {
			for (p=0,i=n-j+1;i<=n;i++) y[++p]=i;
			for (i=1;i<=n;i++) if (sa[i]>j) y[++p]=sa[i]-j;
			for (i=0;i<=m;i++) ww[i]=0;
			for (i=1;i<=n;i++) ww[x[y[i]]]++;
			for (i=1;i<=m;i++) ww[i]+=ww[i-1];
			for (i=n;i>=1;i--) sa[ww[x[y[i]]]--]=y[i];
			for (swap(x,y),x[sa[1]]=p=1,i=2;i<=n;i++)
				x[sa[i]]=cmp(y,sa[i-1],sa[i],j) ? p : ++p;
		}
	}
	void calheight(int *r,int *sa,int n) {
		for (int i=1;i<=n;i++) rank[sa[i]]=i;
		for (int k=0,i=1;i<=n;i++) {
			if (k) k--;
			int j=sa[rank[i]-1];
			while (r[i+k]==r[j+k]) k++;
			height[rank[i]]=k;
		}
	}
}
bool check(int mid) {
	int mx=sa[1],mn=sa[1];
	for (int i=2;i<=n;i++) {
		if (height[i]>=mid) mx=max(mx,sa[i]),mn=min(mn,sa[i]);
		else {
			if (mx-mn>mid) return 1;
			mx=mn=sa[i];
		}
	}
	return mx-mn>mid;
}
int main() {
	while (scanf("%d",&n)!=EOF && n) {
		for (int i=1;i<=n;i++) scanf("%d",&a[i]);
		for (int i=1;i<n;i++) s[i]=a[i+1]-a[i]+100;
		n--;
		Suffix::da(s,sa,n,200);
		Suffix::calheight(s,sa,n);
		int l=0,r=n,ans=0;
		while (l<=r) {
			int mid=(l+r)>>1;
			if (check(mid)) ans=mid,l=mid+1;
			else r=mid-1;
		}
		if (ans<4) puts("0");
		else printf("%d\n",ans+1);
	}
    return 0;
}

 

posted @ 2017-01-11 20:30  MashiroSky  阅读(107)  评论(0编辑  收藏  举报