数位DP习题

例题1

题目大意:求区间内0的个数比1的个数多的数的个数。
题目链接

https://vjudge.net/contest/448380#problem/A

思路:dp [ pos ] [ cnt ] , pos代表枚举到第 pos 位,cnt 代表截止到当前位0的个数比1少的个数。注意 lead 前导零,limit 代表数位的上界。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
using namespace std;
typedef long long ll;

const ll maxx = 10005;
ll dp[40][70];
ll a[maxx];

//lead 前导零  limit 数位上界 
ll dfs(int pos, int cnt, bool lead, bool limit)
{
	if(pos == -1)return	cnt>=32; 
	if(!limit && !lead &&dp[pos][cnt]!=-1)return dp[pos][cnt];
	int up = limit?a[pos]:1;	//根据 limit 判断枚举的上界 up 
	int ans = 0;
	for(int i=0;i<=up;i++)
	{
		if(lead && i==0)ans+=dfs(pos-1,cnt,lead,limit && i==a[pos]);
		else ans+=dfs(pos-1,cnt+(i==0?1:-1),lead && i==0 ,limit && i==a[pos]);
	}
	if(!limit && !lead) dp[pos][cnt] = ans;
	return ans;
}

// 分解数位 
ll solve(ll x)
{
	int pos = 0;
	while(x)
	{
		a[pos++] = x%2;
		x/=2;
	}
	return dfs(pos-1,32,1,1);
}

int main()
{
	memset(dp,-1,sizeof(dp));
	ll l,r;
	scanf("%lld%lld",&l,&r);
	printf("%lld\n",solve(r)-solve(l-1));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bfucs泽泽泽泽泽泽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值