Palindrome
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5698 Accepted Submission(s): 1918
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.
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
Source
题目大意:
给你一个长度为N的字符串,让你在其中添加一些字符,使得字符串变成回文串。
问最少要添加多少个字符能够达到目标。
思路:
我们想要找到原串中最长回文子串(可以不连续),那么我们不妨考虑镜像原串。
那么将原串翻转,然后和原串跑一遍LCS即可.
因为内存不够用,所以再滚动一波数组就行了。
那么ans=n-Lcs;
Ac代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char b[150000];
char a[150000];
int dp[2][5002];
int main()
{
int n;
while(~scanf("%d",&n))
{
int cnt=0;
scanf("%s",a);
for(int i=n-1;i>=0;i--)
{
b[cnt++]=a[i];
}
memset(dp,0,sizeof(dp));
int output=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i-1]==b[j-1])
{
dp[1][j]=dp[0][j-1]+1;
}
else
{
dp[1][j]=max(dp[0][j],dp[1][j-1]);
}
output=max(dp[1][j],output);
}
for(int j=1;j<=n;j++)
{
dp[0][j]=dp[1][j];
dp[1][j]=0;
}
}
printf("%d\n",n-output);
}
}