传送门:【HDU】3518 Boring counting
题目分析:这题呢,我们先构造出后缀数组,求出height数组。然后我们枚举字符串的长度,易知【L,R】内连续的height[i]有共同的前缀,前缀的最长长度为【L+1,R】内所有height的最小值。于是我们可以枚举字符串长度d,然后对该长度找到每一个连续的区间,如果某个区间内最左端l的该前缀和最右端r的该前缀无重叠,即l+d<=r,则++ans。
后缀数组的性质还需要多多掌握啊。
代码如下:
#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 = 1005 ; const int INF = 0x3f3f3f3f ; char s[MAXN] ; int t1[MAXN] , t2[MAXN] , c[MAXN] , xy[MAXN] ; int sa[MAXN] , rank[MAXN] , height[MAXN] ; 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 = 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 , n ) xy[i] = x[y[i]] ; rep ( i , 0 , m ) c[i] = 0 ; rep ( i , 0 , n ) ++ c[xy[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 solve () { int n = strlen ( s ) , ans = 0 ; da ( n + 1 ) ; For ( i , 1 , n / 2 ) { int l = INF , r = -INF ; For ( j , 1 , n ) { if ( height[j] < i ) { if ( r - l >= i ) ++ ans ; l = INF , r = -INF ; } else { l = min ( l , min ( sa[j - 1] , sa[j] ) ) ; r = max ( r , max ( sa[j - 1] , sa[j] ) ) ; } } if ( r - l >= i ) ++ ans ; } printf ( "%d\n" , ans ) ; } int main () { while ( ~scanf ( "%s" , s ) && strcmp ( s , "#" ) ) solve () ; return 0 ; }