palindrome
Time limit:4000/2000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 5246 Accepted Submission (s): 1800
Problem Description A palindrome is a symmetrical string, which is, a string read identically from the left to the right as well as From the right to the left. You-to-write a program which, given a string, determines the minimal number of characters to being inserted into the Stri Ng in order to obtain a palindrome.
As an example, by inserting 2 characters, the string "ab3bd" can is transformed into a palindrome ("Dab3bad" or "Adb3bda") . However, inserting fewer than 2 characters does not produce a palindrome.
Input Your program was 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 is to be considered distinct.
Output Your program was to write to standard output. The first line contains one integer and which is the desired minimal number.
Sample Input
5 AB3BD
Sample Output
2
Source IOI 2000
Recommend Linle | We have carefully selected several similar problems for you:1505 1506 1074 1003 1510 topic: give you a string that asks at least a few letters to be modified before Can make the string a palindrome string. How to solve the problem: the number of characters to be added = the length of the original string-(the length of the longest common subsequence of the original string and the inverse string), and hence the equivalent of the LCS; but the string length is up to 5000 and there is a limit requirement internally, so here we write with a scrolling array. The code is as follows:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int dp[2][5010];//The first dimension is either an odd number or even
char s1[5010];
Char s2[5010];
int main ()
{
int n;
while (scanf ("%d", &n)!=eof)
{
scanf ("%s", S1);
for (int i=0;i<n;i++)//construct S1 inverse string
{
s2[i]=s1[n-i-1];
}
S2[n]= '///Don't forget this
memset (dp,0,sizeof (DP));
for (int i=1;i<=n;i++)
{for
(int j=1;j<=n;j++)
{
if (s1[i-1]==s2[j-1])
{
dp[i% 2][j]=dp[(i-1)%2][j-1]+1;
}
else
{
Dp[i%2][j]=max (dp[(i-1)%2][j],dp[i%2][j-1]);
}}} printf ("%d\n", N-dp[n%2][n]);
}
return 0;
}