题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1090
大水题,随便搞一个O(n^3)的区间DP就A了额。。。
代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std ;
#define cost( l , r ) ( r - l + 1 ) > len[ l ][ r ] ? min( r - l + 1 , COUNT( ( r - l + 1 ) / len[ l ][ r ] ) + 2 + dp( l , l + len[ l ][ r ] - 1 ) ) : ( r - l + 1 )
#define maxn 110
int f[ maxn ][ maxn ] , n , pre[ maxn ][ maxn ] , len[ maxn ][ maxn ] ;
char s[ maxn ] ;
void kmp( ) {
for ( int i = 0 ; i ++ < n ; ) {
pre[ i ][ 1 ] = 0 ;
for ( int k = 2 , j = 0 ; k <= n - i + 1 ; ++ k ) {
for ( ; j && s[ i + j ] != s[ i + k - 1 ] ; j = pre[ i ][ j ] ) ;
if ( s[ i + j ] == s[ i + k - 1 ] ) ++ j ;
pre[ i ][ k ] = j ;
}
for ( int j = i ; j <= n ; ++ j ) {
if ( ! ( ( j - i + 1 ) % ( j - i + 1 - pre[ i ][ j - i + 1 ] ) ) ) {
len[ i ][ j ] = j - i + 1 - pre[ i ][ j - i + 1 ] ;
} else len[ i ][ j ] = j - i + 1 ;
}
}
}
int COUNT( int x ) {
int cnt = 0 ;
for ( ; x ; x /= 10 ) ++ cnt ;
return cnt ;
}
int dp( int l , int r ) {
if ( f[ l ][ r ] ) return f[ l ][ r ] ;
f[ l ][ r ] = cost( l , r ) ;
for ( int i = l ; i < r ; ++ i ) {
f[ l ][ r ] = min( f[ l ][ r ] , dp( l , i ) + dp( i + 1 , r ) ) ;
}
return f[ l ][ r ] ;
}
int main( ) {
scanf( "%s" , s + 1 ) ;
n = strlen( s + 1 ) ;
kmp( ) ;
memset( f , 0 , sizeof( f ) ) ;
printf( "%d\n" , dp( 1 , n ) ) ;
return 0 ;
}