最长公共子序列:https://www.cnblogs.com/wkfvawl/p/9362287.html
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
思路:假设原字符串的序列为S,逆序列为S',所以最少需要补充的字母数 = 原序列S的长度 — S和S'的最长公共子串长度。
注意:仅用静态数组是不可以的,会造成内存超限,即最少要开[5001][5001],所以要使用滚动数组,即for循环的嵌套时,i=0时占用第一行内存i=1时占用第二层内存,当i=2的时候就可以把数据存在i=0的空间里(因为i=0的数据已经没有用了)。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char a[5010];
char b[5010];
int dp[5][5010];
int main()
{
int n;
while(~scanf("%d",&n))
{
memset(a,'\0',sizeof(a));
memset(b,'\0',sizeof(b));
memset(dp,0,sizeof(dp));
scanf("%s",a);
int r=0;
for(int i=n-1; i>=0; i--)
b[r++]=a[i];
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(a[i]==b[j])
dp[(i+1)%2][j+1]=dp[i%2][j]+1;
else
dp[(i+1)%2][j+1]=max(dp[i%2][j+1],dp[(i+1)%2][j]);
}
}
if(n%2==0)
printf("%d\n",n-dp[0][n]);
else
printf("%d\n",n-dp[1][n]);
}
return 0;
}