Light OJ 1032 Fast Bit Calculations(数位DP)

75 篇文章 0 订阅

A bit is a binary digit, taking a logical value of either 1 or 0 (also referred to as "true" or "false" respectively). And every decimal number has a binary representation which is actually a series of bits. If a bit of a number is 1 and its next bit is also 1 then we can say that the number has a 1 adjacent bit. And you have to find out how many times this scenario occurs for all numbers up to N.

解析:简答数位DP。

dp[i][0]是第i+1位为0,0~(1<<i)-1内所有的adjacent bit的个数;

dp[i][1]是第i+1位为1,0~(1<<i)-1内所有的adjacent bit的个数。


[code]:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long LL;

LL dp[35][2];
int n,a[35],b[35],top;

void getBit(int n){
    top = 0;
    while(n){
        a[top++] = n&1;
        n>>=1;
    }
    for(int i = 0;i < top;i++){
        if(i) b[i] = b[i-1]+(a[i]<<i);
        else b[i] = a[i];
    }
}

LL dfs(int i,int s,bool e){
    if(i == -1) return 0;
    if(!e&&dp[i][s]!=-1) return dp[i][s];
    LL res = 0;
    int d,u = e?a[i]:1;
    for(d = 0;d <= u;d++){
        res += dfs(i-1,d,e&&(d==u));
    }
    if(u&&s){
        int tmp = e?b[i-1]+1:(1<<i);
        res += tmp;
    }
    return e?res:dp[i][s]=res;
}

LL sol(int n){
    getBit(n);
    return dfs(top-1,0,1);
}

int main(){
    int i,j,cas,T;
    memset(dp,-1,sizeof(dp));
    scanf("%d",&cas);
    for(T = 1;T <= cas;T++){
        scanf("%d",&n);
        printf("Case %d: %lld\n",T,sol(n));
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值