Fast Bit Calculations
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
Submit
Status
Description
A bit is a binary digit, taking a logical value of either 1 or 0 (also referred to as “true” or “false” respectively). And every decimal number has a binary representation which is actually a series of bits. If a bit of a number is 1 and its next bit is also 1 then we can say that the number has a 1 adjacent bit. And you have to find out how many times this scenario occurs for all numbers up to N.
Examples:
Number Binary Adjacent Bits
12 1100 1
15 1111 3
27 11011 2
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case contains an integer N (0 ≤ N < 231).
Output
For each test case, print the case number and the summation of all adjacent bits from 0 to N.
Sample Input
7
0
6
15
20
21
22
2147483647
Sample Output
Case 1: 0
Case 2: 2
Case 3: 12
Case 4: 13
Case 5: 13
Case 6: 14
Case 7: 16106127360
题意:对于一个数 num ,改成二进制的数 , Adjacent Bits就是这个二进制数中连续的 1 的个数,给你 n,让你求 1—>n里面有多少个Adjacent Bits
题解:数位dp是一种计数用的dp,一般就是要统计一个区间[le,ri]内满足一些条件数的个数,所以可以推断用数位dp来做。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define M 40
#define LL long long
LL dp[M][M][2];
int bit[M];
LL dfs(int pos, LL sum, int pre, bool limit)
{
if(pos == -1) return sum;//返回积累的 11
LL ans = 0;
if(!limit && dp[pos][sum][pre] != -1)
{
return dp[pos][sum][pre];
//记忆化限制条件,避免重复求解
}
int up = limit ? bit[pos] : 1;
for(int i=0; i<=up; i++)
{
if(pre && i)
{
ans += dfs(pos-1, sum+1, i, limit && i==bit[pos]);//sum+1表示出现了一个11
}
else
{
ans += dfs(pos-1, sum, i, limit && bit[pos]==i);
}
}
if(!limit) dp[pos][sum][pre] = ans;//在限制条件外记忆
return ans;
}
LL solve(LL n)
{
int len = 0;
while(n)
{
bit[len++] = n % 2;
n /= 2;
}
return dfs(len-1, 0, 0, 1);
}
int main()
{
LL n;
int t;
scanf("%d", &t);
for(int i=1; i<=t; i++)
{
scanf("%lld", &n);
memset(dp, -1, sizeof(dp));
printf("Case %d: %lld\n", i, solve(n));
}
return 0;
}