原题地址:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=2069
题意:让你求出在[0,n]这范围内,有多少数字的二进制形式中1的数量是3的倍数。
思路:这题很普通的数位dp不一样。平常的都是对10进行除法,但是由于在这题中求的是二进制,所以是对2进行除法。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll dp[100][100][100];//dp[i][j][k]表示当前在第i位,且第i位是j,并且二进制中的模的结果
int cnt, a[100];
ll dfs(int pos, int pre, int mod, int limit) {
ll ans = 0;
if(pos == -1) return mod==0;
if(!limit && dp[pos][pre][mod] != -1) return dp[pos][pre][mod];
int up = limit ? a[pos] : 1;
for(int i = 0; i <= up; i++) {
int mod_x = (mod + i) % 3;
ans += dfs(pos - 1, i, mod_x, limit && i == up);
}
if(!limit) dp[pos][pre][mod] = ans;
return ans;
}
ll solve(ll x) {
cnt = 0;
while(x) {
a[cnt++] = x % 2;
x /= 2;
}
return dfs(cnt - 1, -1, 0, true);
}
int main() {
memset(dp, -1, sizeof(dp));
ll n;
while(~scanf("%lld", &n)) {
printf("Day %lld: Level = %lld\n",n,solve(n)-1);//减1是因为每次都把0算进去了
//如果不想减1的话就在dfs中增加1维sum值,用于记录二进制各位数的和
}
return 0;
}