题目描述:
A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
5 Ab3bd
2
题目意思是,把给定的字符串变成回文字符串,求最少需要添加的字符数。
这题要利用最大公共子序列。一个字符串和它倒过来的字符串的最大公共
子序列,在这个上面添加字符就可以做到最少,使它成为回文字符串。
假设两个两个字符串互为逆, s1 , s2 ;
如果 s1 当前的字符和 s2 当前的字符相同,即 s1[i] == s2[j] , 那么 s1的一段
s1[ 0 , 1 ...i ] 和 s2 当前的一段 s2[ 0 , 1 ....j ] 的最长公共子序列就是
s1[0,1,....i-1] 和 s2[0,1,...j-1] 最大公共子序列的基础上+1,也就是添加了 s1[i] 和 s2[j] 。
如果不相同, s1 当前和 s2 当前最大公共子序列的长度不会增加,等效于
不添加 s1[i] 或者不添加 s2[j] ,取其中的更大者。
写出状态变化:
如果 s1[i] == s2[j] , dp[i][j] = dp[i-1][j-1]+1 ;
否则 dp[i][j] = max( dp[i-1][j] , dp[i][j-1] ) ;
还要利用到滚动数组,因为当前的状态只和前一个状态有关,不然内存过不去。
如有错误,敬请指正。
代码:
#include <stdio.h>
#define max( a , b ) ( a > b ? a : b )
char s1[5005] , s2[5005] ;
int dp[2][5005] ;
int main(){
int n , i = 1 , j = 1 ;
scanf( "%d%s" , &n , s1+1 ) ;
for( i = 1 ; i <= n ; ++i ) s2[i] = s1[n-i+1] ;
for( i = 1 ; i <= n ; ++i )
for( j = 1 ; j <= n ; ++j )
dp[i&1][j] = s1[i] == s2[j] ? dp[(i-1)&1][j-1]+1 : max( dp[(i-1)&1][j] , dp[i&1][j-1] ) ;
printf( "%d\n" , n-dp[n&1][n] ) ;
return 0 ;
}