Palindrome
| Time Limit: 3000MS |
|
Memory Limit: 65536K |
| Total Submissions: 59029 |
|
Accepted: 20505 |
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 is to give you a string that allows you to add at least as many characters as a palindrome string, referring to the idea of the online gods first to reverse the original string and then to find the longest common subsequence of the two strings,
Characters to be added = length of string-common string
It feels good to understand, and then write down the longest common sub-sequence just fine, simple DP AH
There is also a need for attention in the middle, because the topic requires a memory of 65536K, if you use an int to save
DP[5005][5005], there is no doubt memory overrun, a lot of great God is written by scrolling array. Ben Weak weak use short to store DP array, insurance over AH!!! Since int is saved as 4 bytes, and short is saved with only 2 bytes, you know.
Magical short, no hyper memory, #include <stdio.h> #include <string.h> #include <algorithm>using namespace std; Short Dp[5005][5005];char S1[5005],s2[5005];int main () {int N,i,j;int ans;while (~scanf ("%d", &n)) {scanf ("%s", S1); int L = strlen (S1); for (i=0;i<l;i++) {s2[l-i-1]=s1[i];} S2[l] = ' + '; memset (Dp,0,sizeof (DP)); for (i=1;i<=l;i++) {for (j=1;j<=l;j++) {if (s1[i-1]==s2[j-1]) {dp[i][j]=dp[ i-1][j-1]+1;} Elsedp[i][j]=max (Dp[i-1][j],dp[i][j-1]);}} printf ("%d\n", L-dp[l][l]);} return 0;}
POJ 1159 Palindrome--palindrome series, dynamic planning