POJ 3252 Round Numbers 数位DP

本文介绍了一种使用动态规划方法来计算两个给定数值范围内特定二进制子序列出现次数的算法。该算法首先将给定的整数转换为二进制形式,并通过递归函数遍历所有可能的二进制位组合来统计符合要求的子序列数量。

注意只有高位放了1之后才能开始统计

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <string>
#include <iostream>
#include <map>
#include <cstdlib>
#include <list>
#include <set>
#include <queue>
#include <stack>

using namespace std;

typedef long long LL;

int lim[256],len = 0;
LL f[40][40][40];

void getlim(LL N) {
    memset(lim,0,sizeof(lim));
    memset(f,-1,sizeof(f));
    len = 0;
    LL tmp = N;
    while(tmp) {
        lim[len++] = tmp & 1;
        tmp >>= 1;
    }
}

LL dfs(int now,int cz,int co,int bound,int first) {
    LL &note = f[now][cz][co];
    if(now == 0) {
        if(first) return cz >= co;
        else return 0;
    }
    if(!bound && note != -1 && first) {
        return note;
    }
    int m = bound ? lim[now - 1] : 1;
    LL ret = 0;
    for(int i = 0;i <= m;i++) {
        if(first) {
            ret += dfs(now - 1,cz + !i,co + i,bound && i == lim[now - 1],first);
        } else {
            if(i == 0) ret += dfs(now - 1,cz,co,0,0);
            else ret += dfs(now - 1,0,1,bound && i == lim[now - 1],1);
        }
    }
    if(!bound && first) note = ret;
    return ret;
}

int main() {
    LL N,M;
    while(cin >> N >> M) {
        LL ret1,ret2;
        getlim(M); ret1 = dfs(len,0,0,1,0);
        getlim(N - 1); ret2 = dfs(len,0,0,1,0);
        cout << ret1 - ret2 << endl;
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/rolight/p/3886680.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值