UVa 11584

题意:给定一个字符串,判断能划分成尽量少的回文串的数量。

dp[i]代表的状态为字符串前i个字符所能划分成的最少回文串的数量。判断回文串可以用递归来判断。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;

char str[1024];
int dp[1024];
const int inf = 0x7f7f7f7f;

bool is_ok(const int l, const int r){
    if(l >= r) return true;
    return str[l] == str[r] && is_ok(l + 1, r - 1);
}

int main()
{
    int T; cin >> T;
    while(T--){
        scanf("%s", str + 1);
        int len = strlen(str + 1);
        memset(dp, inf, sizeof(dp)); dp[0] = 0;
        for(int i = 1; i <= len; ++i){
            for(int j = 0; j < i; ++j){
                if(is_ok(j+1, i))
                    dp[i] = min(dp[i], dp[j] + 1);
            }
        }
        cout << dp[len] << endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/kunsoft/p/5312674.html