# NOI 题库 8471 题解

## 8471   切割回文

3
abaacca
abcd
abcba

1
3
0

f[ i ] 表示前 i 个需要切割的次数
 1 #include "bits/stdc++.h"
2
3 using namespace std ;
4 const int maxN = 1100 ;
5 const int INF = 2147483647 ;
6
7 int Judge [ maxN ][ maxN ] ;
8 char s[ maxN ] ;
9 int f[ maxN ] ;
10
11 inline int gmin ( int x , int y ) { return x < y ? x : y ; }
12
13 inline void Init ( const int n ) {
14         for ( int i=1 ; i<=n ; ++i ) Judge[ i ][ i ] = true ;
15         for(int i=1 ; i<=n ; ++i ) {
16                 for(int L=0 ; i-L>=1 && i+L<=n ; ++L ) {
17                         if ( s [ i - L ] != s [ i + L ] ) break;
18                         else Judge[ i - L ][ i + L ] = true ;
19                 }
20                 for(int L=0 ; i-L>=1 && i+L+1<=n ; ++L ) {
21                         if ( s [ i - L ] != s [ i + L + 1 ] ) break;
22                         else Judge[ i - L ][ i + L + 1 ] = true ;
23                 }
24         }
25 }
26
27 int main ( ) {
28         int T ;
29         scanf ( "%d" , &T ) ;
30         while ( T-- ) {
31                 memset ( f , 0x7f , sizeof ( f ) ) ;
32                 memset ( Judge , false , sizeof ( Judge ) ) ;
33                 scanf ( "%s" , s + 1 ) ;
34                 int Len = strlen ( s + 1 ) ;
35                 Init ( Len ) ;
36
37                 for ( int i=1 ; i<=Len ; ++i ) {
38                         if ( Judge [ 1 ][ i ] ) {f[ i ] = 0 ; continue ;}
39                         for ( int j=1 ; j<i ; ++j ) {
40                                 if ( Judge[ j + 1 ][ i ] ) {
41                                         f[ i ] = gmin ( f[ i ] , f[ j ] + 1 ) ;
42                                 }
43                         }
44                 }
45                 printf ( "%d\n" , f[ Len ] ) ;
46         }
47         return 0 ;
48 } 
View Code

2016-10-27  12:50:52

posted @ 2016-10-27 12:53  SHHHS  阅读(196)  评论(0编辑  收藏