zoukankan      html  css  js  c++  java
  • 周赛A题

    Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu
     

    Description

    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

    6

    abcd

    aaaa

    abc

    aab

    abababaabababa

    pqrsabcdpqrs

    Sample Output

    Case 1: 3

    Case 2: 0

    Case 3: 2

    Case 4: 1

    Case 5: 0

    Case 6: 9

    题解:通过插入把给的字符串变为回文串,求出最小操作数。

    状态转移:dp[i][j] = min(dp[i+1][j],dp[i][j+1])+1; (s[i]!=s[j])

                        dp[i][j] = dp[i+1][j-1];  (s[i]==s[j])

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    int t,k,dp[1010][1010];
    char s[1010];
    int main()
    {
        cin>>t;
        k=1;
        while (t--)
        {
            cin >> s;
            int len = strlen(s);
            memset(dp,0,sizeof(dp));
            for (int i = len - 1; i >= 0; i--)
                for (int 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;
                   }
           cout<<"Case "<<k++<<": "<<dp[0][len-1]<<endl;
        }
        return 0;
    }
  • 相关阅读:
    Problem C: 爬楼梯
    Problem E: 倒水(Water)
    Problem H: tmk买礼物
    HDU 1078 FatMouse and Cheese
    POJ 3186 Treats for the Cows
    POJ 1661 Help Jimmy
    POJ 1458 Common Subsequence
    2018-软工机试-D-定西
    2018-软工机试-F-庙会
    2018-软工机试-C-和你在一起
  • 原文地址:https://www.cnblogs.com/hfc-xx/p/4731166.html
Copyright © 2011-2022 走看看