poj3252 Round Numbers (不允许前导0的二进制数位dp)

题目链接 题意:问某区间中,round number 的个数是多少。所谓round number,当且仅当一个数的二进制表示中,‘0’的个数大于等于‘1’的个数。 思路:简单数位dp..和windy数那道题类似,都是不允许前导0.。。所以在dfs中要加一维判断前面是否有非0的数。。。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年03月17日 星期四 16时17分07秒
 4File Name :code/poj/3252.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <ctime>
19#define fst first
20#define sec second
21#define lson l,m,rt<<1
22#define rson m+1,r,rt<<1|1
23#define ms(a,x) memset(a,x,sizeof(a))
24typedef long long LL;
25#define pi pair < int ,int >
26#define MP make_pair
27
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33int l,r;
34int digit[35];
35int dp[35][35][35]; //dp[i][j][k]表示长度为i,有j个0,k个1的方案数。
36
37int dfs( int pos,int cnt0,int cnt1,bool limit,bool prehasnonzero)  //不允许前导0,所以要加prehasnonzero这个参数
38								    //来确定是否位数减少了....
39{
40    if (pos==0) return cnt0>=cnt1;
41    if (!limit&&dp[pos][cnt0][cnt1]!=-1) return dp[pos][cnt0][cnt1];
42    int mx = limit?digit[pos]:1; //2进制。。最大是1.  
43    int res = 0;
44    if (prehasnonzero)
45    {
46	for ( int i = 0 ; i <= mx;  i++)
47	{
48	    res+=dfs(pos-1,i==0?cnt0+1:cnt0,i==1?cnt1+1:cnt1,limit&&i==mx,true);
49	}
50    }
51    else
52    {
53	for ( int i = 0 ; i <= mx  ; i++)
54	{
55	    if (i==0)
56	    {
57		res+=dfs(pos-1,0,0,limit&&i==mx,false);
58	    }
59	    else
60	    {
61		res+=dfs(pos-1,0,1,limit&&i==mx,true);
62	    }
63	}
64    }
65	if (!limit) dp[pos][cnt0][cnt1] = res;
66	return res;
67    }
68int solve ( int n)
69{
70    ms(digit,0);
71    int len =  0 ;
72
73    while (n)
74    {
75	digit[++len] = n % 2;
76	n /= 2;
77    }
78
79    return  dfs(len,0,0,true,false);
80}
81int main()
82{
83	#ifndef  ONLINE_JUDGE 
84	freopen("code/in.txt","r",stdin);
85  #endif
86
87	ms(dp,-1);
88	cin>>l>>r;
89	int ans = solve ( r ) - solve ( l - 1 );
90	cout<<ans<<endl;
91
92  #ifndef ONLINE_JUDGE  
93  fclose(stdin);
94  #endif
95    return 0;
96}