PalindromeTime
limit:MS
Memory Limit:65536KB
64bit IO Format:%i64d &%i64u SubmitStatus
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 left. You-to-write a program which, given a string, determines the minimal number of characters to being inserted into the STR ing 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 is-to-write to standard output. The first line contains one integer and which is the desired minimal number.
Sample Input
5ab3bd
Sample Output
2
Test instructions: Let you add a minimum number of letters in the original string to make the original string palindrome.
Idea: The minimum number of letters to be replenished = the length of the original sequence-the length of the longest common substring of the original string and the inverse string. The DP stores the same number of letters from I to J.
PS: Because 5000*5000 is definitely hyper-memory, we introduce the knowledge of scrolling arrays here. Scrolling arrays are ideal for use in two-dimensional DP and are arrays in large, can save memory, eliminate the hidden danger of super memory!
Scrolling array explanation
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include < algorithm> #include <set> #include <queue>using namespace Std;const int Inf=0x3f3f3f3f;char str1[5010]; Char str2[5010];int dp[2][5010];int Main () { int n,i,j; while (~SCANF ("%d", &n)) { getchar (); for (i=1;i<=n;i++) { scanf ("%c", &str1[i]); Str2[n-i+1]=str1[i]; } Memset (Dp,0,sizeof (DP)); for (i=1;i<=n;i++) for (j=1;j<=n;j++) { if (Str1[i]==str2[j]) 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;}
POJ 1159-palindrome (dp_ palindrome string + scrolling array)