poj 3252

求[l,r]里面有多少数在二进制的表示下0的个数大于1的个数。
二进制的数位dp,
需要注意的是数种0的数量需要从最高位是1的情况下开始计算。比如00000010(2)的0 的个数不是7而是1.

#include <cstdio>
#include <cstring>

using namespace std;
typedef long long LL;

LL bits[40],d[40][40][40];
LL a,b; 
LL dp(int pos,int num0,int num1,int dif,int hap){
	if(pos == 0 ) return num0 >= num1;
	if(dif && d[pos][num0][num1] != -1) return d[pos][num0][num1];
	LL x = dif ? 1 : bits[pos];
	LL ans = 0;
	for(int i = 0;i <= x;i++){
		if(!i) ans += dp(pos-1,num0+(hap?1:0),num1,dif||i<x,hap);
		else ans += dp(pos-1,num0,num1+1,dif||i<x,1);
	} 
	if(dif ) d[pos][num0][num1] = ans;
	return ans;
}

LL cal(LL x){
	int cnt = 0;
	while(x){
		bits[++cnt] = x & 1;
		x >>= 1;
	}
	return dp(cnt,0,0,0,0);
} 
int main(){
	while(~scanf("%lld%lld",&a,&b)){
		memset(d,-1,sizeof(d));
		printf("%d\n",cal(b) - cal(a-1));
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/winhcc/article/details/88956730
今日推荐