UVa 11584:Partitioning by Palindromes(DP)

17 篇文章 0 订阅

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=847&page=show_problem&problem=2631

题意:输入一个由小写字母组成的字符串,你的任务是把它划分成尽量少的回文串。例如,racecar本身就是回文串;fastcar只能分成7个单字母的回文串,aaadbccb最少分成3个回文串:aaa,d,bccd。字符串长度不超过1000。(本段摘自《算法竞赛入门经典(第2版)》)

分析:
设dp[i]为到第i个位置为止,最少的划分次数,dp[i] = min(dp[j] + 1 && s[j + 1~i]是回文串)

代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <cctype>
#include <stack>
#include <set>

using namespace std;

const int maxn = 1000 + 5, INF = 1e9;

int T, l, tmp;
int dp[maxn];
char s[maxn];

bool judge(int x, int y)
{
    for (int i = x, j = y; i < j; ++i, --j)
        if (s[i] != s[j])
            return false;
    return true;
}

int main()
{
    scanf("%d", &T);
    for (int C = 0; C < T; ++C)
    {
        scanf("%s", s + 1);
        l = strlen(s + 1);
        dp[0] = 0;
        for (int i = 1; i <= l; ++i)
        {
            tmp = INF;
            for (int j = 0; j < i; ++j)
                if (judge(j + 1, i))
                    tmp = min(tmp, dp[j] + 1);
            dp[i] = tmp;
        }
        printf("%d\n", dp[l]);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值