传送门:【HDU】4552 怪盗基德的挑战书
题目分析:答案就是所有后缀和串s的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 = 100005 ; char s[MAXN] ; int t1[MAXN] , t2[MAXN] , c[MAXN] , xy[MAXN] ; int sa[MAXN] , rank[MAXN] , height[MAXN] ; int dp[MAXN][17] ; 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 x , int y ) { int k = 0 ; while ( ( 1 << ( k + 1 ) ) <= y - x + 1 ) ++ k ; return min ( dp[x][k] , dp[y - ( 1 << k ) + 1][k] ) ; } int lcp ( int x , int y ) { x = rank[x] ; y = rank[y] ; return x < y ? rmq ( x + 1 , y ) : rmq ( y + 1 , x ) ; } void solve () { int n = strlen ( s ) ; int ans = n , minv = MAXN ; da ( n + 1 ) ; init_RMQ ( n ) ; rep ( i , 1 , n ) ans = ( ans + lcp ( 0 , i ) ) % 256 ; printf ( "%d\n" , ans ) ; } int main () { while ( ~scanf ( "%s" , s ) ) solve () ; return 0 ; }
上面的代码用了RMQ,但实际上是不需要的,那是我对后缀数组的不了解造成的。其实只要从rank[0]向两边扫就OK了的。
代码如下:
void solve () { int n = strlen ( s ) ; int ans = n ; da ( n + 1 ) ; int x = rank[0] , y = x , t = MAXN ; while ( y > 0 ) { t = min ( t , height[y --] ) ; ans = ( ans + t ) % 256 ; } y = x + 1 , t = MAXN ; while ( y <= n ) { t = min ( t , height[y ++] ) ; ans = ( ans + t ) % 256 ; } printf ( "%d\n" , ans ) ; }