UVA11384-Help is needed for Dexter 动态规划

题目:给定一个数字N,列出1-N序列,每次选中1-N中的某一个数字不断减序列中的任意个数,使得序列中的数字最后都变为0,求该步骤的最少步数。

分析:N = 3, 序列:1 2 3  对1、2减1 变为0 1 3 ;再对1 3 减1 变为 0 0 2 ;再对2减2 变为0 0 0 。得出:总共需要3步。

           N = 6, 序列:1 2 3 4 5 6 对4 、5、6 减4 变为0 1 2 ;此时序列相当于N=3时的序列,得出:总共需要1 + 3 = 4步。

           N = 7, 序列:1 2 3 4 5 6 7对4 、5、6、 7 减4 变为0 1 2 3;此时序列相当于N=3时的序列,得出:总共需要1 + 3 = 4步。

解析:对所求N先分奇偶,再除2。对于偶数,在dp[N/2]的基础之上再加1。对于奇数,等于其N-1的偶数需要的步数。

注意:本题要求算到1e9,但是一维数组只能算到1e8,但是我发现dp[1e8] = 27,dp[1e9] = 30,所以我利用不断手动二分,算出28、29、30对应的dp下标。

代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<cstring>
#include<string>
#include<set>
#include<cmath>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn = 1e8;
typedef long long LL;


int n;

int dp[maxn];
void Table()
{
    memset(dp,0,sizeof dp);
    dp[1] = 1;
    dp[2] = 2;
    for(int i = 3; i <= maxn; ++i)
    {
        if(i % 2 == 1)
        {
            dp[i] = dp[i-1];
        }
        else{
            dp[i] = 1 + dp[i / 2];
        }
    }

}
void See()
{
    for(int i = 1; i <= 100; ++i)
    {
        cout << dp[i] << " ";
        if(i % 10 == 0){
            cout << endl;
        }
    }
    //134217728   28
    //536870912   30
    //268435456   29
}
int main()
{
    Table();
    while(scanf("%d",&n) != EOF)
    {
        if(n <= 100000000)
        {
            printf("%d\n", dp[n]);
        }
        if(n > 100000000 && n < 134217728)
        {
            cout << 27 << endl;
        }
        else if(n >= 134217728 && n < 268435456)
        {
            cout << 28 << endl;
        }
        else if(n >= 268435456 && n < 536870912)
        {
            cout << 29 << endl;
        }
        else if(n >= 536870912)
        {
            cout << 30 << endl;
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值