Palindrome
Time limit 3000 ms
Memory limit 65536 kB
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
思路分析:
运用动态规划法。
求最长公共子序列;
再滚动数组的方法进行dp;
用总长度减去最大公共子序列即所要的答案。
代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n;
char a[5200],b[5200]; //开两个数组
int dp[3][5200];
int main()
{
while(~scanf("%d",&n))
{
scanf("%s",a);
int l=0;
memset(dp,0,sizeof(dp));
for(int j=strlen(a)-1; j>=0; j--) //将字符串倒向存在b数组中
b[l++]=a[j];
for(int i=0; i<l; i++) //这是一个求最大公共序列的两层for循环
for(int j=0; j<l; 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]);//滚动数组
printf("%d\n",l-(max(dp[0][l],dp[1][l]))); //总长-最大公共序列=需要补的字符个数
}
return 0;
}