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.
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.
题意:给你一个字符串,问最少添加几个字母能使该字符串变为回文串。先输入字符串的长度,再输入要转换为回文串的字符串。
思路:用dp[i][j]表示该字符串从下标为i的字母到下标为j的字母即这j-i+1个字母要想成为回文串最少要添加的字母。对于该字符串的任意一段字符都有两种情况进行添加字母成为回文串。第一种情况:如果st[i]=st[j],则dp[i][j]=dp[i+1][j-1]。第二种情况:如果st[i]!=st[j],则dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1。最后输出dp[0][len-1]即整个字符串要成为回文串最少需要添加的字母个数。
Sample Input
5 Ab3bd
Sample Output
2
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
short dp[5005][5005];
char st[5005];
int main()
{
//freopen("lalala.text","r",stdin);
int len;
while(~scanf("%d",&len))
{
scanf("%s",st);
for(int i=0; i<len-1; i++)
{
dp[i][i]=0; //对于长度为1的字符串进行初始化
if(st[i]==st[i+1]) //对于长度为2的字符串进行初始化,如果俩字母相等则不需添加
dp[i][i+1]=0;
else //如果俩字母不相等则只需添加一个字母即可成为回文串
dp[i][i+1]=1;
}
dp[len-1][len-1]=0;
for(int i=2; i<=len; i++) //枚举任意一串字符的长度
for(int j=0; j<len-i; j++) //枚举任意一串字符的起始位置
{
if(st[j]==st[j+i])
dp[j][j+i]=dp[j+1][j+i-1];
else
dp[j][j+i]=min(dp[j][j+i-1],dp[j+1][j+i])+1;
}
printf("%d\n",dp[0][len-1]);
}
return 0;
}<strong>
</strong>