lightoj 1033 - Generating Palindromes(区间dp) - dblank

lightoj 1033 - Generating Palindromes(区间dp)

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]表示是s[i]到s[j]变成回文串的最小代价,dp[1][len]]就是答案。对于一个dp[i][j]因为之前的状态我们是得到了的,如果是s[i] == s[j],那么代价就是min(dp[i][j], dp[i+1][j-1]),如果不相同的话,dp[i][j] = min(dp[i+1][j], dp[i][j-1])+1。这个时候我们决策的就是插入是s[i] 还是 s[j] 因为 dp[i+1][j] 和 dp[i][j-1] 已经得到了,也就是那部分已经是回文串了。

#include<iostream>  
#include<cstdio>  
#include<algorithm>  
#include<map>  
#include<cstring>  
#include<map>  
#include<set>  
#include<queue>  
#include<stack>  
#include<cmath>  
using namespace std;  
const double eps = 1e-10;  
const int inf = 0x3f3f3f3f, N = 1e2 + 10, Mod = 1000000007;  
typedef long long ll;  
int str[N][N];  
char s[N];  
int dp[N][N];  
int main()  
{  
    int t;  
    cin>>t;  
    for(int cas = 1; cas<=t; cas++)  
    {  
        scanf("%s", s+1);  
        memset(dp, 0, sizeof(dp));  
        int len = strlen(s+1);  
        for(int i = len; i>=1; i--)//注意循环的顺序  
            for(int j = i + 1; j<=len; j++)  
            {  
                dp[i][j] = min(dp[i+1][j], dp[i][j-1])+1;  
                if(s[i] == s[j])  
                    dp[i][j] = min(dp[i][j], dp[i+1][j-1]);  
            }  
        printf("Case %d: %d\n", cas, dp[1][len]);  
    }  
    return 0;  
}

 

相关文章

发表新评论