UVA 11584 Partitioning by Palindromes 区间dp

点击打开题目链接

一个由小写字母组成的字符串,划分成尽量少的回文串。

感觉和最长上升子序列差不多,区间dp,方法不对,导致TLE了好久。

dp[ R ] = min(dp[ R ], dp[ L - 1 ] + 1)( L <= R, ch[ L ][ R ] 是回文);

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

const int MAXN = 1000 + 10;
int dp[MAXN];
char ch[MAXN];

bool isPalind(int L, int R)     //判断ch[L]...ch[R]是否回文
{
    while (L < R)
    {
        if (ch[L] != ch[R]) return false;
        L++;
        R--;
    }
    return true;
}

int main()
{
    int n;
    scanf("%d", &n);
    while (n--)
    {
        scanf("%s", ch + 1);        //下标从1开始
        int Len = strlen(ch + 1);
        dp[0] = 0;
        for (int R = 1; R <= Len; R++)
        {
            dp[R] = R;              //初始化
            for (int L = 1; L <= R; L++)
            {
                if (isPalind(L, R))     //状态转移
                    dp[R] = min(dp[R], dp[L - 1] + 1);
            }
        }
        printf("%d\n", dp[Len]);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值