Palindrome
Time limit:3000 Ms |
|
Memory limit:65536 K |
Total submissions:53647 |
|
Accepted:18522 |
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
Source
IOI 2000
How many characters do you add to convert the string into a return string?
We need to find the longest public subsequence of the string and its reverse sequence. In this way, the LCS must be of the background, while others will not, therefore, the characters must be inserted at the corresponding position to make them symmetric, and the entire string can be retrieved.
#include <map> #include <set> #include <list> #include <stack> #include <queue> #include <vector> #include <cstdio> #include <cmath> #include <cstring> #include <iostream> #include <algorithm> using namespace std;char str1[5010];char str2[5010];int dp[2][5010];int main(){int len;while (~scanf("%d", &len)){scanf("%s", str1);for (int i = 0; i < len; i++){str2[i] = str1[len - i - 1];}str2[len] = '\0';memset (dp, 0, sizeof(dp) );for (int i = 1; i <= len; i++){for (int j = 1; j <= len; j++){if (str1[i - 1] == str2[j - 1]){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", len - dp[len % 2][len]);}}
Poj1159 -- palindrome