【uva-11584】Partitioning by Palindromes(dp)

本文介绍了一种使用动态规划解决字符串回文划分问题的方法。通过三次嵌套循环实现了字符串的有效划分,复杂度约为L^3,成功在0.052秒内通过测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 粗略的复杂度是L^3,长度最大是1000,,没敢做,之后发现其实这个复杂度的系数也不大,可以过,而且很快。

dp[j] = dp[i - 1] + 1 (if(str[i] ~ str[j]为回文)

14327451 11584 Partitioning by Palindromes Accepted C++ 0.052 2014-10-09 09:33:17
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> pill;
const int maxn = 1111;
char str[maxn];
int   dp[maxn];
bool is_part(int i,int j){
    while(i < j){
        if(str[i] != str[j])
            return false;
        i ++;
        j --;
    }
    return true;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%s",str);
        int L = strlen(str);
        for(int i = 0 ; i <= L; i ++) dp[i] = i + 1;
        for(int j = 0 ; j < L; j ++) // L
            for(int i = 0 ; i <= j ; i ++){ // L
                if(is_part(i,j)){ // L
                    if(i - 1 >= 0)
                        dp[j] = min(dp[j],dp[i - 1] + 1);
                    else
                        dp[j] = 1;
                }
            }
        printf("%d\n",dp[L - 1]);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值