POJ 1159-Palindrome (dp _ return string + scrolling array)
Palindrome
Time Limit:3000 MS
Memory Limit:65536KB
64bit IO Format:% I64d & % I64uSubmit Status
Description
A palindrome is a regular rical 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 "adb3me "). 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
5Ab3bd
Sample Output
2
Question: let you add the minimum number of letters to the original string to make the original string a text string.
Train of Thought: the minimum number of letters to be supplemented = the length of the original sequence-the length of the longest common substring of the original string and the inverse string. Dp stores the number of identical letters from I to j.
PS: Because 5000*5000 is definitely super memory, so here we introduce the knowledge of the scrolling array. The scrolling array is suitable for Two-Dimensional DP, And the array is very large, which can save memory and eliminate the hidden danger of overmemory!
Rolling Array
#include
#include
#include
#include
#include #include
#include
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;}