LightOJ 1032 数位DP

版权声明:抱最大的希望,为最大的努力,做最坏的打算。 https://blog.csdn.net/qq_37748451/article/details/86588695
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

题意:输入n,要求从0到n的所有数的二进制数里面总共有多少“11”。   求每个数出现11的次数之和

思路: 一看就是数位dp的标准题目,问题就在于如何去写状态转移方程

将输入的数转化为二进制之后进行数位dp。

dp[i][j][k]表示i位数前一位是j(由于二进制只可能是0或1)已经存在k个11的总数。

直接上代码去理解吧

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define PI acos(-1.0)
#define E 1e-6
#define MOD 1000000007
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
ll dp[40][2][40];//i位数,前一位是j,已经存在k个11的总数
int digit[40];
ll dfs(int pos,int pre,int st,bool limit)
{
    if(pos==0)return st;
    if(!limit&&dp[pos][pre][st]!=-1)return dp[pos][pre][st];
    ll ans=0;
    int end=limit?digit[pos]:1;
    for(int i=0; i<=end; i++)
        ans+=dfs(pos-1,i,st+(pre&&i),limit&&(i==end));
    if(!limit)
        dp[pos][pre][st]=ans;
    return ans;
}
ll get(int x)
{
    int bj=0;
    while(x)
        digit[++bj]=x%2,x/=2;
    return dfs(bj,0,0,1);
}
int main()
{
    memset(dp,-1,sizeof(dp));
    int t,o=1;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        printf("Case %d: %lld\n",o++,get(n));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37748451/article/details/86588695