【POJ】1743 Musical Theme 【后缀数组】

传送门:【POJ】1743 Musical Theme


题目分析:这题和HDU3518做法差不多。首先将序列差分,然后构造后缀数组,接下来我们二分重复的串的长度k,然后看height[i]连续大于等于k的里面的最左端L是否和最右端重叠,如果不重叠则修改下界,否则如果找不到则修改上界。最后看找到的长度是否大于等于4(差分后少了一个数),有的话输出这个长度,否则输出0。


代码如下:


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;

typedef long long LL ;

#define rep( i , a , b ) for ( int i = ( a ) ; i <  ( b ) ; ++ i )
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define clr( a , x ) memset ( a , x , sizeof a )
#define cpy( a , x ) memcpy ( a , x , sizeof a )

const int MAXN = 20005 ;

int s[MAXN] ;
int t1[MAXN] , t2[MAXN] , c[MAXN] , xy[MAXN] ;
int sa[MAXN] , rank[MAXN] , height[MAXN] ;
int n ;

bool cmp ( int *r , int a , int b , int d ) {
	return r[a] == r[b] && r[a + d] == r[b + d] ;
}

void getHeight ( int n , int k = 0 ) {
	For ( i , 0 , n ) rank[sa[i]] = i ;
	rep ( i , 0 , n ) {
		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 = 200 ) {
	int i , d = 1 , p = 0 , *x = t1 , *y = t2 , *t ;
	for ( i = 0 ; i < m ; ++ i ) c[i] = 0 ;
	for ( i = 0 ; i < n ; ++ i ) ++ c[x[i] = s[i]] ;
	for ( i = 1 ; i < m ; ++ i ) c[i] += c[i - 1] ;
	for ( i = n - 1 ; i >= 0 ; -- i ) sa[-- c[x[i]]] = i ;
	for ( ; p < n ; d <<= 1 , m = p ) {
		for ( p = 0 , i = n - d ; i < n ; ++ i ) y[p ++] = i ;
		for ( i = 0 ; i < n ; ++ i ) if ( sa[i] >= d ) y[p ++] = sa[i] - d ;
		for ( i = 0 ; i < m ; ++ i ) c[i] = 0 ;
		for ( i = 0 ; i < n ; ++ i ) ++ c[xy[i] = x[y[i]]] ;
		for ( i = 1 ; i < m ; ++ i ) c[i] += c[i - 1] ;
		for ( i = n - 1 ; i >= 0 ; -- i ) sa[-- c[xy[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] , d ) ? p - 1 : p ++ ;
		}
	}
	getHeight ( n - 1 ) ;
}

int check ( int k ) {
	int L = MAXN , R = -1 ;
	For ( i , 2 , n ) {
		if ( height[i] < k ) {
			if ( L + k <= R ) return 1 ;
			L = MAXN , R = -1 ;
		} else {
			L = min ( L , min ( sa[i - 1] , sa[i] ) ) ;
			R = max ( R , max ( sa[i - 1] , sa[i] ) ) ;
		}
	}
	return L + k <= R ;
}

void solve () {
	rep ( i , 0 , n ) scanf ( "%d" , &s[i] ) ;
	-- n ;
	rep ( i , 0 , n ) s[i] = s[i + 1] - s[i] + 100 ;
	da ( n + 1 ) ;
	int l = 0 , r = n ;
	while ( l < r ) {
		int m = ( l + r + 1 ) >> 1 ;
		if ( check ( m ) ) l = m ;
		else r = m - 1 ;
	}
	if ( l >= 4 ) printf ( "%d\n" , l + 1 ) ;
	else printf ( "0\n" ) ;
}

int main () {
	while ( ~scanf ( "%d" , &n ) && n ) solve () ;
	return 0 ;
}


你可能感兴趣的:(poj)