Description
A palindrome is a symmetrical 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 “Adb3bdA”). 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
5 Ab3bd
Sample Output
2
The meaning of the question: give n, which means The length of the string given next is n. Insert a few characters at least to make the string become a text string.
Idea: Set the original string to a, reverse the string to b, and subtract the length of the string The longest common subsequence of a and b is sufficient.
Note:
- If you use %c to input, remember to getchar
- Even after using the longest common subsequence, opening the dp array [5050][5050] will cause the memory to exceed the limit. In this case, you need to use Rolling array for processing, since we only need to ask for dp[n][n], the space in the previous part can actually be reused. For example, after 1->2 is stored, we need 3 is saved, but there is no need to open up space, because the space occupied by the previous 1 is no longer needed, so we can save 3 to the position of 1, that is, 3->1, and so on 4-> 2. dp only needs to open to [2][5050], that is, i%2 for each part.
- By the way, pay attention to the distinction between subsequences and strings. Subsequences are not required to meet continuity, but strings need to be continuous.
1 #include
2 #include
3 #include<string.h>
4 #include
5 using namespace std;
6
7 char a[5050],b[5050];
8 int dp[2][5050];
9 int main()
10 {
11 int n;
12 cin>>n;
13 memset(dp,0,sizeof(dp));
14 memset(a,'