Descriptiona Palindrome is a symmetrical string, which is, a string of read identically from a rig HT to 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 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
This problem is similar to editing distances, using dynamic programming to solve:
Use DP (I,J) to indicate that the array from I to J makes it the number of characters to be added to the palindrome string
Then the dynamic programming equation is
1.min (DP (I+1,J) +1,DP (i,j-1) +1) (A[i]!=a[j])
2.DP (I+1,j-1) (A[i]=a[j])
This problem because n up to 5000, so using the int type of two-dimensional array will be hyperspace, you can change the int to short type, you can also use scrolling array ....
#include"iostream"#include"CString"#include"Cstdio"using namespacestd;Const intmaxn=5010;CharA[MAXN]; Shortdp[2][MAXN]; ShortMin ShortA1, ShortA2) { returnA1<a2?a1:a2;}intMain () {intN; while(SCANF ("%d", &n)! =EOF) {scanf ("%s", A +1); for(inti=n-1; i>=1; i--) { for(intj=i+1; j<=n;j++) {Dp[i%2][j]=min (dp[i%2][j-1]+1, dp[(i+1)%2][j]+1); if(a[j]==A[i]) dp[i%2][j]=dp[(i+1)%2][j-1]; }} cout<<dp[1][n]<<Endl; } return 0;}
Dynamic planning of the fifth week of training G Palindrome series