poj3252 Round Numbers (不允许前导0的二进制数位dp)
题目链接 题意:问某区间中,round number 的个数是多少。所谓round number,当且仅当一个数的二进制表示中,‘0’的个数大于等于‘1’的个数。 思路:简单数位dp..和windy数那道题类似,都是不允许前导0.。。所以在dfs中要加一维判断前面是否有非0的数。。。
/* ***********************************************
Author :111qqz
Created Time :2016年03月17日 星期四 16时17分07秒
File Name :code/poj/3252.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6int l,r;
7int digit[35];
8int dp[35][35][35]; //dp[i][j][k]表示长度为i,有j个0,k个1的方案数。
1int dfs( int pos,int cnt0,int cnt1,bool limit,bool prehasnonzero) //不允许前导0,所以要加prehasnonzero这个参数
2 //来确定是否位数减少了....
3{
4 if (pos==0) return cnt0>=cnt1;
5 if (!limit&&dp[pos][cnt0][cnt1]!=-1) return dp[pos][cnt0][cnt1];
6 int mx = limit?digit[pos]:1; //2进制。。最大是1.
7 int res = 0;
8 if (prehasnonzero)
9 {
10 for ( int i = 0 ; i <= mx; i++)
11 {
12 res+=dfs(pos-1,i==0?cnt0+1:cnt0,i==1?cnt1+1:cnt1,limit&&i==mx,true);
13 }
14 }
15 else
16 {
17 for ( int i = 0 ; i <= mx ; i++)
18 {
19 if (i==0)
20 {
21 res+=dfs(pos-1,0,0,limit&&i==mx,false);
22 }
23 else
24 {
25 res+=dfs(pos-1,0,1,limit&&i==mx,true);
26 }
27 }
28 }
29 if (!limit) dp[pos][cnt0][cnt1] = res;
30 return res;
31 }
32int solve ( int n)
33{
34 ms(digit,0);
35 int len = 0 ;
1 while (n)
2 {
3 digit[++len] = n % 2;
4 n /= 2;
5 }
1 return dfs(len,0,0,true,false);
2}
3int main()
4{
5 #ifndef ONLINE_JUDGE
6 freopen("code/in.txt","r",stdin);
7 #endif
1 ms(dp,-1);
2 cin>>l>>r;
3 int ans = solve ( r ) - solve ( l - 1 );
4 cout<<ans<<endl;
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}