HDU4105 Electric wave 动态规划

转载注明出处  http://blog.csdn.net/moedane


传送门 http://acm.hdu.edu.cn/showproblem.php?pid=4105


题意

给一个长度为n的数字串,在其中加尽可能多的空格,使得分隔出来的数字呈现波谷、波峰、波谷、波峰……这样的规律(即小、大、小、大……这里的大小都是严格的)。求能添加的最多的空格数。n <= 100


思路

o(n^3)的dp。

我的状态设为dp[i][j][2],表示做到前i个数字,且最后一个数字在原串中的区间是[j,i],且最后一个数是波峰/波谷(1/0)的时候,分割成的数字个数。

那么转移就是

dp[i][j][0] = max(dp[j-1][k][1] + 1), [j,i] < [k,j-1]

dp[i][j][1] = max(dp[j-1][k][0] + 1), [j,i] > [k,j-1]

由于题目要求第一个数字必须是波谷,则初始化为

dp数组memset为负无穷大,且dp[i][0][0] = 1,( 0 <= i < n)

答案就是max(dp[n-1][i][0] , dp[n-1][i][1]),( 0 <= i < n)

在转移的时候需要比较两个数的大小,写一个比较的函数即可。


代码

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <vector>
#include <queue>
#include <stack>
#include <fstream>
#include <map>
#include <set>
#define bug puts("here");

using namespace std;

typedef long long ll;

const int maxn = 2 * 101000;
const ll mod = 1e9+7;
const int inf = 0x3f3f3f3f;
const double PI = atan(1.0) * 4.0;
const double eps = 1e-8;

int dp[110][110][2];
char s[110];
int n;

int scmp(int a,int b,int x, int y){ // [a,b] < [x,y] : -1
    while(s[a]  == '0' && a <= b) a++;
    while(s[x]  == '0' && x <= y) x++;
    if(b-a > y-x) return 1;
    if(b-a < y-x) return -1;
    while(s[a]  == s[x]  && a <= b && x <= y){
        a ++;
        x ++;
    }
    if(a <= b && x <= y)
        return s[a]  < s[x]  ? -1 : 1;
    else if (x <= y) return -1;
    else if (a <= b) return 1;
    else return 0;
}

int main()
{
    while(~scanf("%d",&n))
    {
        scanf("%s",s);
        memset(dp, -0x3f, sizeof dp);
        for(int i=0;i<n;i++) dp[i][0][0] = 1;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<=i;j++)
            {
                for(int k=0;k<j;k++)
                {
                    if(scmp(k,j-1,j,i) == 1) dp[i][j][0] = max(dp[i][j][0] , dp[j-1][k][1] + 1);
                    if(scmp(k,j-1,j,i) == -1) dp[i][j][1] = max(dp[i][j][1] , dp[j-1][k][0] + 1);
                }
            }
        }
        int ans = 0;
        for(int i=0;i<n;i++)
            ans = max(ans , max(dp[n-1][i][0] , dp[n-1][i][1]));
        printf("%d\n",ans - 1);
    }
}<strong>
</strong>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值