【算法竞赛入门经典】动态规划初步 例题9-7 UVa11584

【算法竞赛入门经典】动态规划初步 例题9-7 UVa11584

例题UVa11584

这里写图片描述

Input

Input begins with the number n of test cases. Each test case consists of a single line of between 1 and 1000 lowercase letters, with no whitespace within.

Output

For each test case, output a line containing the minimum number of groups required to partition the input into groups of palindromes.

Sample Input

3
racecar
fastcar
aaadbccb

Sample Output

1
7
3

分析

利用dp[i]表示第1个字符到第i个字符最少的回文串数量。
这样,便利第0个到第i-1个字符,顺序记作j,这样,如果a[j]……a[i]构成回文串的话,那么dp[i]=dp[j]+1
这样遍历j取最小之后
dp[n]就是答案了

样例实现代码

#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#define maxn 1000+5
#define INF 100000
using namespace std;
int dp[maxn], isp[maxn][maxn];
string a;
bool ispf(int i, int j) {
    if (i >= j)
        return true;
    if (a[i] != a[j])
        return false;
    if (isp[i][j] >= 0)
        return isp[i][j];
    isp[i][j] = ispf(i + 1, j - 1);
    return isp[i][j];
}
int main() {
    int T;
    cin >> T;
    getchar();
    while (T--) {
        getline(cin, a);
        int n = a.size();
        a = " " + a;
        memset(dp, 0, sizeof(dp));
        memset(isp, -1, sizeof(isp));
        for (int i = 1; i <= n; i++) {
            dp[i] = dp[i - 1] + 1;
            for (int j = 0; j<i; j++) {
                if (ispf(j, i)) {
                    dp[i] = min(dp[i], dp[j-1] + 1);
                }
            }
        }
        cout << dp[n] << endl;
    }
    return 0;
}

结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值