【LightOJ】 - 1032(数位DP基础)

题目链接:

http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1032

题目大意:现在给你一个数N代表0~N的范围,求这个范围内 某个数转化为2进制之后有相邻的两个1的数的数量

思路: 基本上就是数位dp的基础题目了,其中cnt是在某次DFS从高位到最后一位的出现总共的次数,

推荐一篇我的入门时候的博文:https://blog.csdn.net/wentong_Xu/article/details/82502877感觉都差不多的记忆化搜索吧,

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
ll dp[35][2][35];
ll a[35];

ll dfs(ll pos,ll pre,ll cnt,ll limit)
{
    if(pos==0)
        return cnt;
    if(limit&&dp[pos][pre][cnt]!=-1)
        return dp[pos][pre][cnt];

    ll up=limit?1:a[pos];
    ll ans=0;
    for(ll i=0; i<=up; i++)
    {
        ans+=dfs(pos-1,i,cnt+(pre==1&&i==1),limit||i!=up);
    }
    if(limit)
        dp[pos][pre][cnt]=ans;
    return ans;
}

ll solve(ll x)
{
    memset(dp,-1,sizeof(dp));
    int pos=0;
    while(x)
    {
        a[++pos]=x%2;
        x/=2;
    }
    return dfs(pos,-1,0,0);
}

int main()
{
    int t,kase=1;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        cin>>n;
        cout<<"Case "<<kase++<<": ";
        cout<<solve(n)<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值