dp基础习题(4.11)

http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=34398

题意:将一个单词划分为几个回文串使得回文串的数量尽量少

思路:预处理,确定s[i ] - s[j]是否为回文串。dp[i]表示的是从0到i的字符串最少回文串的个数,将dp[i]初始化为 i + 1代表每个回文串的长度都为1时回文串的个数。然后进行状态转移:dp[i] = min{dp[j - 1] + 1,dp[i]}前提是s[i]-s[j]为回文串。由状态方程可知j应从i开始,到0

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
#include <algorithm>
#include <list>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdlib>
using namespace std;
char c[1005];
bool s[1005][1005];
int dp[1005];
int n;
bool judge(int a,int b)
{
    if(a < 0 || a >= n || b < 0 || b >= n)
        return false;
    return true;
}
void init()
{
    memset(s,false,sizeof(s));
    int t = 1;
    for(int i = 0; i < n; i ++)
    {
        s[i][i] = true;
    }
    for(int i = 0; i < n; i ++)
    {
        t = 1;
        while(1)
        {
            if(judge(i - t,i + t) == false || c[i - t] != c[i + t])//等于t的时候是不成立的
                break;
            s[i + t][i - t] = true;
            t ++;
        }
        t = 1;
        while(1)
        {
            if(judge(i - t + 1,i + t) == false || c[i - t + 1] != c[i + t])//等于t的时候是不成立的
                break;
            s[i + t][i - t + 1]  = true;
            t ++;
        }

    }
}


int main()
{
    //freopen("in.txt","r",stdin);
    int T;
    scanf("%d",&T);
    while(T --)
    {
        scanf("%s",c);
        n = strlen(c);
        init();
        for(int i = 0; i < n; i ++)
        {
            dp[i] = i + 1;
            for(int j = 0; j <= i; j ++)
            {
                if(s[i][j] == true)
                {
                    if(j != 0)
                        dp[i] = min(dp[j - 1] + 1,dp[i]);
                    else
                        dp[i] = min(1,dp[i]);
                }
            }
        }
        printf("%d\n",dp[n - 1]);
    }
    return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值