题目链接:
http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1032
题目大意:现在给你一个数N代表0~N的范围,求这个范围内 某个数转化为2进制之后有相邻的两个1的数的数量
思路: 基本上就是数位dp的基础题目了,其中cnt是在某次DFS从高位到最后一位的出现总共的次数,
推荐一篇我的入门时候的博文:https://blog.csdn.net/wentong_Xu/article/details/82502877感觉都差不多的记忆化搜索吧,
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define ll long long
using namespace std;
ll dp[35][2][35];
ll a[35];
ll dfs(ll pos,ll pre,ll cnt,ll limit)
{
if(pos==0)
return cnt;
if(limit&&dp[pos][pre][cnt]!=-1)
return dp[pos][pre][cnt];
ll up=limit?1:a[pos];
ll ans=0;
for(ll i=0; i<=up; i++)
{
ans+=dfs(pos-1,i,cnt+(pre==1&&i==1),limit||i!=up);
}
if(limit)
dp[pos][pre][cnt]=ans;
return ans;
}
ll solve(ll x)
{
memset(dp,-1,sizeof(dp));
int pos=0;
while(x)
{
a[++pos]=x%2;
x/=2;
}
return dfs(pos,-1,0,0);
}
int main()
{
int t,kase=1;
scanf("%d",&t);
while(t--)
{
int n;
cin>>n;
cout<<"Case "<<kase++<<": ";
cout<<solve(n)<<endl;
}
return 0;
}