方法 LCS
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 #include<stdio.h> 5 #include<cmath> 6 using namespace std; 7 8 short int dp[5002][5002]; char str[5123]; 9 int main( ) 10 { 11 int N; 12 while( scanf("%d",&N) != EOF ) 13 { 14 scanf("%s",str+1); int len = strlen( str+1 ); 15 memset( dp,0,sizeof(dp) ); int Max = 0; 16 for( int i = len; i >= 1; i-- ) 17 for( int j = 1; j <= i - 1; j++ ){ 18 if( str[i] == str[j] ) dp[i][j] = dp[i+1][j-1]+1; 19 else dp[i][j] = max( dp[i+1][j],dp[i][j-1] ); 20 if( j == i-1 ) Max = max( Max,dp[i][j]*2); 21 else Max = max( Max,dp[i][j]*2+1 ); 22 } 23 cout<<N-Max<<endl; 24 } 25 return 0; 26 }