題目連結:http://lightoj.com/volume_showproblem.php?problem=1033
1033 - Generating Palindromes
![]() | PDF (English) | Statistics | Forum |
Time Limit: 2 second(s) | Memory Limit: 32 MB |
By definition palindrome is a string which is not changed when reversed. "MADAM" is a nice example of palindrome. It is an easy job to test whether a given string is a palindrome or not. But it may not be so easy to generate a palindrome.
Here we will make a palindrome generator which will take an input string and return a palindrome. You can easily verify that for a string of length n, no more than (n - 1) characters are required to make it a palindrome. Consider "abcd" and its palindrome "abcdcba" or "abc" and its palindrome "abcba". But life is not so easy for programmers!! We always want optimal cost. And you have to find the minimum number of characters required to make a given string to a palindrome if you are only allowed 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. You may safely assume that the length of the string will be positive and no more than 100.
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)
題目大意 : 給你一串字元串,求最少添加多少個字元,使該串變成回文串,可以在任意地方添加
解析: 比賽時,完全懵逼了,不知道該從何入手,下去看大牛們的部落格,才知道是區間DP, 把該
字元串變成兩個串,一個向頭周遊,一個向尾部周遊,dp [ i ] [ j ] 表示長度為 j - i + 1 的字元
串需要添加的最小個數,如果是 s[ i ] == s[ j ] , dp[ i ] [ j ] = ;dp[i + 1] [ j - 1] ;
不相等, dp [ i ] [ j ] = min (dp[ i + 1] [ j ] , dp[ i ] [ j - 1] ) + 1;
具體見下面代碼:
#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;
}