lightoj - 1032 Fast Bit Calculations (数位dp:求前n个数中含11的总个数)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sdz20172133/article/details/86590192

1032 - Fast Bit Calculations
    PDF (English)    Statistics    Forum
Time Limit: 2 second(s)    Memory Limit: 32 MB
A bit is a binary digit, taking a logical value of either 1or 0 (also referred to as "true" or "false"respectively). And every decimal number has a binary representation which isactually a series of bits. If a bit of a number is 1 and its next bit isalso 1 then we can say that the number has a 1 adjacent bit. Andyou 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 summationof all adjacent bits from 0 to N.

Sample Input
Output for Sample Input
7

0

6

15

20

21

22

2147483647

Case 1: 0

Case 2: 2

Case 3: 12

Case 4: 13

Case 5: 13

Case 6: 14

Case 7: 16106127360
 

题意:对于一个数 n ,改成二进制的数 , Adjacent Bits就是这个二进制数中连续的 1 的个数(含有11个数),给你 n,让你求 1—>n里面有多少个Adjacent Bits 

分析:

数位DP的模板题,dp[pos][sta][pre]表示到当前位置pos,前面有多少个11,前一位是pre的,答案是多少。

如果前一位是1,后以为是1,记录下来,否则向下枚举即可。

///求前n个数的二进制形式含有11个数的和
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=40;
typedef long long ll;
int n;
int dig[maxn];
ll dp[maxn][maxn][2];
///dp[pos][sta][pre]表示到当前位置pos,前面有多少个11,前一位是pre的,答案是多少
ll dfs(int pos,int sta,int limit,int pre)
{
    if(pos<0) return sta;
    if(!limit&&dp[pos][sta][pre]!=-1)
    	 return dp[pos][sta][pre];
    ll ans=0;
    int up=(limit?dig[pos]:1);  ///二进制的时候为1,十进制的时候9
    for(int i=0;i<=up;i++)
    {
        if(pre&&i)///前一个是1,后一个也是1。记录个数
        	ans+=dfs(pos-1,sta+1,limit&&i==up,i);
        else 
            ans+=dfs(pos-1,sta,limit&&i==up,i);
    }
    if(!limit)dp[pos][sta][pre]=ans;
    return ans;
}
ll solve(int n)
{
    int len=0;
    memset(dp,-1,sizeof(dp));
    while(n)
    {
        dig[len++]=n%2; ///转化为二进制
        n/=2;
    }
    return dfs(len-1,0,1,0);
}
int main()
{
    int T,cas=1;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        printf("Case %d: %lld\n",cas++,solve(n));
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/86590192