Problem descriptiona 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.
Inputyour 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.
Outputyour 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: A string is provided. It must contain at least a few characters to convert the string to a text string.
Idea: reverse the string to an LCS, and then ask for N minus the length of the longest common substring, but note that the string can be up to 5000, if the two-dimensional DP array is enabled by 5000, it will exceed the memory. Here we use a rolling array, because in the calculation of LCS, the I changes only differ by 1, therefore, you can scroll through the remainder of 2.
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;char s1[5005],s2[5005];int dp[2][5005],n;void LCS(){ int i,j; memset(dp,0,sizeof(dp)); for(i = 1;i<=n;i++) { for(j = 1;j<=n;j++) { int x = i%2; int y = 1-x; if(s1[i-1]==s2[j-1]) dp[x][j] = dp[y][j-1]+1; else dp[x][j] = max(dp[y][j],dp[x][j-1]); } }}int main(){ int i,j; while(~scanf("%d",&n)) { scanf("%s",s1); for(i = 0;i<n;i++) s2[i] = s1[n-1-i]; s2[i] = '\0'; LCS(); printf("%d\n",n-dp[n%2][n]); } return 0;}