LightOJ 1044 - Palindrome Partitioning

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;
}
posted @ 2017-04-17 20:33  aiterator  阅读(199)  评论(0编辑  收藏  举报