题目链接:http://poj.org/problem?id=3252
题意:求范围内数字二进制下0的个数大于等于1的个数的数的个数。
数位dp,dp(l,zero,one,fz)记录当前第l位时0的个数1的个数和当前位是否是前导零中的部分,dfs转移就行。
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define fr first 4 #define sc second 5 #define cl clear 6 #define BUG puts("here!!!") 7 #define W(a) while(a--) 8 #define pb(a) push_back(a) 9 #define Rint(a) scanf("%d", &a) 10 #define Rll(a) scanf("%I64d", &a) 11 #define Rs(a) scanf("%s", a) 12 #define Cin(a) cin >> a 13 #define FRead() freopen("in", "r", stdin) 14 #define FWrite() freopen("out", "w", stdout) 15 #define Rep(i, len) for(int i = 0; i < (len); i++) 16 #define For(i, a, len) for(int i = (a); i < (len); i++) 17 #define Cls(a) memset((a), 0, sizeof(a)) 18 #define Clr(a, x) memset((a), (x), sizeof(a)) 19 #define Full(a) memset((a), 0x7f7f7f, sizeof(a)) 20 #define lrt rt << 1 21 #define rrt rt << 1 | 1 22 #define pi 3.14159265359 23 #define RT return 24 #define lowbit(x) x & (-x) 25 #define onecnt(x) __builtin_popcount(x) 26 typedef long long LL; 27 typedef long double LD; 28 typedef unsigned long long ULL; 29 typedef pair<int, int> pii; 30 typedef pair<string, int> psi; 31 typedef pair<LL, LL> pll; 32 typedef map<string, int> msi; 33 typedef vector<int> vi; 34 typedef vector<LL> vl; 35 typedef vector<vl> vvl; 36 typedef vector<bool> vb; 37 38 const int maxn = 34; 39 int digit[maxn]; 40 LL dp[maxn][maxn][maxn][2]; 41 42 int k; 43 LL l, r; 44 45 LL dfs(int l, int zero, int one, bool fz, bool flag) { 46 if(l == 0) return zero >= one; 47 if(!flag && ~dp[l][zero][one][fz]) return dp[l][zero][one][fz]; 48 LL ret = 0; 49 int pos = flag ? digit[l] : 1; 50 Rep(i, pos+1) { 51 if(i == 0 && fz) ret += dfs(l-1, 0, one, fz, flag&&(pos==i)); 52 else ret += dfs(l-1, zero+(i==0), one+(i==1), false, flag&&(pos==i)); 53 } 54 if(!flag) dp[l][zero][one][fz] = ret; 55 return ret; 56 } 57 58 LL f(LL x) { 59 int pos = 0; 60 while(x) { 61 digit[++pos] = x & 1; 62 x >>= 1; 63 } 64 return dfs(pos, 0, 0, true, true); 65 } 66 67 signed main() { 68 //FRead(); 69 Clr(dp, -1); 70 while(cin >> l >> r) { 71 cout << f(r) - f(l-1) << endl; 72 } 73 RT 0; 74 }