思路:很显然答案是长度减去字符串和它反转串的LCS,不过由于内存限制,需要使用滚动数组。(short也可以水过)
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 6 const int N = 5001; 7 char a[N], b[N]; 8 int dp[2][N]; 9 10 int main () 11 { 12 int n; 13 while ( scanf("%d", &n) != EOF ) 14 { 15 scanf("%s", a); 16 for ( int i = 0; i < n; i++ ) 17 { 18 b[i] = a[n - 1 - i]; 19 } 20 memset( dp, 0, sizeof(dp) ); 21 for ( int i = 1; i <= n; i++ ) 22 { 23 for ( int j = 1; j <= n; j++ ) 24 { 25 if( a[i - 1] == b[j - 1] ) 26 { 27 dp[i % 2][j] = dp[(i - 1) % 2][j - 1] + 1; 28 } 29 else 30 { 31 dp[i % 2][j] = max( dp[i % 2][j - 1], dp[(i - 1) % 2][j] ); 32 } 33 } 34 } 35 printf("%d ", n - dp[n % 2][n]); 36 } 37 return 0; 38 }