Saruman’s Level Up
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
题意:
给你一个数,问你在小于等于这个数的数中,有多少二进制含有3的倍数个1的数。举个例子:7的二进制是111,算一个,13的二进制是1011等等。
题解:
数位dp,也是记忆化搜索的模板题,这种题我都没怎么做过,得多练一下。首先dfs有三个参数,pos:当前搜索到的二进制的位置,maxn:是否达到上界,rem:对三的余数。
未达到上界同时这种状态搜索过了就可以return,ma就代表当前位置是0还是1,若不是上界就可以把搜索到的状态赋值给dp数组,然后return,有一种情况就是全0他的余数也是0,所以需要-1;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int wei[100],len;
ll dp[100][5];
ll dfs(int pos,int maxn,int rem)
{
if(pos<=0)
return rem==0;
if(dp[pos][rem]!=-1&&!maxn)
return dp[pos][rem];
int ma=maxn?wei[pos]:1;
ll ans=0;
for(int i=0;i<=ma;i++)
{
ans+=dfs(pos-1,maxn&&i==ma,(rem+i)%3);
}
if(!maxn)
dp[pos][rem]=ans;
return ans;
}
int main()
{
ll n;
while(~scanf("%lld",&n))
{
memset(dp,-1,sizeof(dp));
ll ret=n;
len=0;
while(ret)
{
wei[++len]=ret%2;
ret/=2;
}
printf("Day %lld: Level = %lld\n",n,dfs(len,1,0)-1);
}
}