zoukankan      html  css  js  c++  java
  • LightOJ 1044

    A palindrome partition is the partitioning of a string such that each separate substring is a palindrome.

    For example, the string "ABACABA" could be partitioned in several different ways, such as {"A","B","A","C","A","B","A"}, {"A","BACAB","A"}, {"ABA","C","ABA"}, or {"ABACABA"}, among others.

    You are given a string s. Return the minimum possible number of substrings in a palindrome partition of s.

    Input

    Input starts with an integer T (≤ 40), denoting the number of test cases.

    Each case begins with a non-empty string s of uppercase letters with length no more than 1000.

    Output

    For each case of input you have to print the case number and the desired result.

    Sample Input

    3
    AAAA
    ABCDEFGH
    QWERTYTREWQWERT
    

    Output for Sample Input

    Case 1: 1
    Case 2: 8
    Case 3: 5
    

    题目大意就是说对于每一个一个字符串,都可以分解成若干个回文串。

    现在让你求所给字符串分解成若干回文串的最小数量。

    显然,分解成若干回文串的最大数量就是回文串的长度。

    建立dp[i]代表前i个字符分解成若干回文串的最小数量。

    那么枚举前i个字符中的j,如果使得在字符串[j,i]区间是回文串, 那么对于

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

    代码如下:

    #include<bits/stdc++.h>
    using namespace std;
     
    bool judge(int x, int y, string &str)
    {
        while(x < y)
        {
            if(str[x] != str[y])
                return false;
            x ++, y --;
        }
        return true;
    }
     
    void solve(int cases)
    {
        string str;
        cin >> str;
        vector<int> dp(str.size()+1, str.size() + 1);
        dp[0] = 0;
        for(int i=1; i<str.size()+1; ++ i)
        {
            dp[i] = i;
            for(int j=1; j<=i; ++ j)
            {
                if(judge(j-1, i-1, str))
                    dp[i] = min(dp[i], dp[j-1] + 1);
            }
        }
        cout << "Case " << cases << ": "  << dp[str.size()] << endl;
    }
     
    int main()
    {
        ios::sync_with_stdio(false);
     
        int t;
        cin >> t;
        for(int i=1; i<=t; ++ i)
            solve(i);
        return 0;
    }
    
  • 相关阅读:
    MAC之基本命令(持续更新)
    Mac下android_sdk配置环境变量
    Eclipse最常用10大快捷键
    Android之使用Jsoup抓取网络数据
    MAC之curl命令
    MAC之cat命令
    Android之FileOutputStream与openFileOutput()的区别
    C# 数字语音wav 提示。。。。。。。。。。。
    HttpWebRequest 获取验证码的图片 并针对有验证码的网页进行Winform登陆。
    经常开车,坐车的朋友请进(看后对你绝对有好处)
  • 原文地址:https://www.cnblogs.com/aiterator/p/6724701.html
Copyright © 2011-2022 走看看