Title Link: http://lightoj.com/volume_showproblem.php?problem=1033
1033-generating palindromes
|
PDF (中文版) |
Statistics |
Forum |
Time Limit:2 second (s) |
Memory limit:32 MB |
By definition palindrome was a string which is not the changed when reversed. "MADAM" is a nice example of palindrome. It is an easy job to test whether a given string was a palindrome or not. But it may is not being so easy to generate a palindrome.
Here we'll make a palindrome generator which would take an input string and return a palindrome. You can easily verify. A string of length n, no more than (n-1) characters is required to mak E it a palindrome. Consider "ABCD" and its palindrome "ABCDCBA" or "abc" and its palindrome "ABCBA". But life isn't so easy for programmers!! We always want optimal cost. And you had to find the minimum number of characters required to make a given string to a palindrome if you were only Allo Wed to insert characters at any position of the string. Input
Input starts with an integer T (≤200), denoting the number of test cases.
Each case contains a string of lowercase letters denoting the string for which we want to generate a palindrome. Safely assume that the length of the string would be positive and no more than. Output
For each case, print the case number and the minimum number of characters required to make string to a palindrome.
Sample Input |
Output for Sample Input |
6 Abcd Aaaa Abc AaB Abababaabababa Pqrsabcdpqrs |
Case 1:3 Case 2:0 Case 3:2 Case 4:1 Case 5:0 Case 6:9 |
Problem SETTER:MD. Kamruzzaman Special Thanks:jane ALAM JAN (MODIFIED DESCRIPTION, DATASET)
The main topic: give you a string, the minimum number of characters to add, so that the string into a palindrome, you can add anywhere
Analysis: The game, completely confused, do not know where to start, go down to see Daniel's blog, just know is the interval DP, the
The string becomes two strings, one to the head, one to the tail, and DP [i] [j] for characters with a length of j-i + 1
The minimum number of strings to add, if s[i] = = s[J], dp[i] [j] =;DP [i + 1] [j-1];
Unequal, DP [i] [j] = min (dp[i + 1] [j], dp[i] [j-1]) + 1;
See the following code for details:
#include <iostream>
#include <algorithm>
#include <map>
#include <string>
#include <cstdio>
#include <cstring>
#include <cctype>
#include <cmath>
# Define N 1009
using namespace std;
const int inf = 0X3F3F3F3F;
const int mod = 1000003;
int dp[n][n];
Char S[n];
int main ()
{
int T, I, j, cnt = 0;
CIN >> T;
while (t--)
{
scanf ("%s", s);
int len = strlen (s);
memset (DP, 0, sizeof (DP));
for (i = len-1; I >= 0, i--)
{for
(j = i + 1; j < Len; j + +)
{
if (s[i] = = S[j]) dp[i][j] = Dp[i + 1][j-1];
else Dp[i][j] = min (dp[i + 1][j], dp[i][j-1]) + 1;
}
}
printf ("Case%d:%d\n", ++cnt, dp[0][len-1]);
}
return 0;
}