2018湖南多校第三场 G-Saruman’s Level Up(数位dp)

Description

Saruman’s army of orcs and other dark minions continuously mine and harvest lumber out of the land surrounding his mighty tower for N continuous days. On day number i, Saruman either chooses to spend resources on mining coal and harvesting more lumber, or on raising the level (i.e., height) of his tower. He levels up his tower by one unit only on days where the binary representation of i contains a total number of 1’s that is an exact multiple of 3. Assume that the initial level of his tower on day 0 is zero. For example, Saruman will level up his tower on day 7 (binary 111), next on day 11 (binary 1011) and then day 13, day 14, day 19, and so on. Saruman would like to forecast the level of his tower after N days. Can you write a program to help?

Input

The input file will contain multiple input test cases, each on a single line. Each test case consists of a positive integer N < 1016, as described above. The input ends on end of file.

Output

For each test case, output one line: “Day N: Level = L”, where N is the input N, and L is the number of levels after N days.

Sample Input

2
19
64

Sample Output

Day 2: Level = 0
Day 19: Level = 5
Day 64: Level = 21

Hint

题目大意:给你一个数,让你求1到这个数中有多少个数化成二进制后数字1的个数是3的倍数。
解题思路:只要学了数位dp,应该就能做出这一题来,我也是在做这一题的时候现学的数位dp,看了好几个数位dp的题,感觉代码差不多都是类似的,主要是找条件,这一题的条件就是“1的个数是3的倍数”。这里有一篇比较好的数位dp博客 浅谈数位DP ,想学的可以去看看,过程确实挺难想的

AC代码:
#include
#include
#include
#include
#include

using namespace std;

long long a, dp[100][100]; //注意开long long
int num[100], k;

long long dfs(int len, int sum1, bool limet)
{
    if(len == 0) {
        if(sum1 % 3 == 0 && sum1 != 0) //注意0余3也为0
            return 1;
        return 0;
    }
    if(!limet && dp[len][sum1]) {
        return dp[len][sum1];
    }
    long long cnt = 0;
    int maxx = (limet ? num[len] : 1);
    for(int i = 0; i <= maxx; i ++) {
        if(i == 0) {
            cnt += dfs(len-1, sum1, limet && i == maxx);
        }else {
            cnt += dfs(len-1, sum1+1, limet && i ==  maxx);
        }
    }
    return limet ? cnt : dp[len][sum1] = cnt;
}

long long solve(long long n)
{
    memset(dp, 0, sizeof(dp));
    memset(num, 0 ,sizeof(num));
    k = 1;
    while(n > 0) {
        num[k ++] = n%2;
        n /= 2;
    }
    return dfs(k, 0, true);
}

int main()
{
    while(~scanf("%lld", &a)) {
        printf("Day %lld: Level = %lld\n", a, solve(a));
    }
    return 0;
}


你可能感兴趣的:(ACM_动态规划)