Palindrome
Problem Description
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.
Input
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.
Output
Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
Sample Input
5
Ab3bd
Sample Output
2
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char pa[5011];
char st[5011];//存储逆字符串
int ma[2][5011];//当前最优解
int main()
{
int N;
int i;
int l;
int j;
while(scanf("%d",&N)!=EOF)
{
scanf("%s",pa);
l=0;
memset(ma,0,sizeof(ma));//初始化数组
for(i=N-1;i>=0;i--)
st[l++]=pa[i];
for(i=1;i<=N;i++)
{
for(j=1;j<=N;j++)//从 1 开始防止数组越界
{
if(pa[i-1]==st[j-1])
ma[i%2][j]=ma[(i-1)%2][j-1]+1;
else
ma[i%2][j]=max(ma[i%2][j-1],ma[(i-1)%2][j]);
}
}
printf("%d\n",N-ma[N%2][N]);
}
return 0;
}