传送门:【URAL】1297 Palindrome
题目分析:将s串倒过来接到原串的后面,中间用'$'隔开,然后我们构造后缀数组和height数组,接着我们RMQ预处理,接下来枚举串的每个点作为回文串的中心,分别以该点为奇回文串中心以及偶回文串中心求LCP,此时向左和向右的串的LCP即以这个点作为中心的回文串的扩展半径,求半径的话我们就对原串位置以及倒过来后的相应位置做LCP。
代码如下:
#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 = 2005 ; char s[MAXN] ; int t1[MAXN] , t2[MAXN] , c[MAXN] , xy[MAXN] ; int sa[MAXN] , rank[MAXN] , height[MAXN] ; int dp[MAXN][12] ; int 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 = 128 ) { int *x = t1 , *y = t2 ; rep ( i , 0 , m ) c[i] = 0 ; rep ( i , 0 , n ) ++ c[x[i] = s[i]] ; rep ( i , 1 , m ) c[i] += c[i - 1] ; rev ( i , n - 1 , 0 ) sa[-- c[x[i]]] = i ; for ( int d = 1 , p = 0 ; p < n ; d <<= 1 , m = p ) { p = 0 ; rep ( i , n - d , n ) y[p ++] = i ; rep ( i , 0 , n ) if ( sa[i] >= d ) y[p ++] = sa[i] - d ; rep ( i , 0 , m ) c[i] = 0 ; rep ( i , 0 , n ) ++ c[xy[i] = x[y[i]]] ; rep ( i , 1 , m ) c[i] += c[i - 1] ; rev ( i , n - 1 , 0 ) sa[-- c[xy[i]]] = y[i] ; swap ( x , y ) ; p = 0 ; x[sa[0]] = p ++ ; rep ( i , 1 , n ) x[sa[i]] = cmp ( y , sa[i - 1] , sa[i] , d ) ? p - 1 : p ++ ; } getHeight ( n - 1 ) ; } void init_RMQ ( int n ) { For ( i , 1 , n ) dp[i][0] = height[i] ; for ( int j = 1 ; ( 1 << j ) <= n ; ++ j ) { for ( int i = 1 ; i + ( 1 << j ) - 1 <= n ; ++ i ) { dp[i][j] = min ( dp[i][j - 1] , dp[i + ( 1 << ( j - 1 ) )][j - 1] ) ; } } } int RMQ ( int L , int R ) { int k = 0 ; while ( ( 1 << ( k + 1 ) ) <= R - L + 1 ) ++ k ; return min ( dp[L][k] , dp[R - ( 1 << k ) + 1][k] ) ; } int lcp ( int a , int b ) { a = rank[a] , b = rank[b] ; return a < b ? RMQ ( a + 1 , b ) : RMQ ( b + 1 , a ) ; } void solve () { int n1 = strlen ( s ) ; int n2 = n1 ; int n = n1 + 1 + n2 ; s[n1] = '$' ; s[n] = 0 ; rep ( i , 0 , n1 ) s[n - i - 1] = s[i] ; da ( n + 1 ) ; init_RMQ ( n ) ; int t = 0 , ans = 0 ; rep ( i , 0 , n1 ) { int x = lcp ( i , n - i - 1 ) ; if ( x * 2 - 1 > t ) { t = x * 2 - 1 ; ans = i - x + 1 ; } int y = lcp ( i , n - i ) ; if ( y * 2 > t ) { t = y * 2 ; ans = i - y ; } } rep ( i , ans , ans + t ) printf ( "%c" , s[i] ) ; printf ( "\n" ) ; } int main () { while ( ~scanf ( "%s" , s ) ) solve () ; return 0 ; }