您的位置:首页 > 其它

UVALive 4864 数位dp

2013-05-08 17:03 113 查看
Start with an integer, N0, which is greater than 0. Let N1 be the number of ones in the binary representation of N0. So, if N0 = 27, N1 = 4. For all i > 0, let Ni be the number of ones in the binary representation of Ni-1. This sequence will always converge to one. For any starting number, N0, let K be the minimum value of i 0 for which Ni = 1. For example, if N0 = 31, then N1 = 5, N2 = 2, N3 = 1, so K = 3.

Given a range of consecutive numbers, and a value X, how many numbers in the range have a K value equal to X?

64位同时为1时即转换为了64以下的数转换到1的步数,所以首先打个表,之后枚举数位之和就ok了。

View Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using std::cout;
using std::cin;
using std::endl;
typedef long long LL;
int const N = 64;
int step
,bit[N+10],ln;
LL lo,hi;
int x;
LL dp

[2];
int getsum1(int n)
{
int sum=0;
int num=n;
for(;n;sum+=n%2,n>>=1);
if(sum==1)return 1;
if(step[sum])return step[sum]+1;
step[num]=getsum1(sum)+1;
}
void pre()
{
step[1]=0;
for(int i=2;i<=64;i++)
{
if(!step[i])
step[i]=getsum1(i);
}
}
LL getsum2(int t,int pre,int rest,int limit)
{
if(rest<0)return 0;
if(!t)return (rest==0);
int up=(limit?bit[t]:1);
LL ans=0;
if(!limit&&dp[t][rest][pre]!=-1)return dp[t][rest][pre];
for(int i=0;i<=up;i++)
{
ans+=getsum2(t-1,i,rest-i,limit&&i==up);
}
if(!limit&&dp[t][rest][pre]==-1)dp[t][rest][pre]=ans;
return ans;
}
LL getsum3(LL n)
{
if(n<=0)return 0;
for(ln=0;n;bit[++ln]=n%2,n>>=1);
LL ans=0;
if(x==0)
return 1;
if(x==step[1]+1)
ans+=getsum2(ln,0,1,1)-1;
for(int i=2;i<=ln;i++)
if(x==step[i]+1)
ans+=getsum2(ln,0,i,1);
return ans;
}
int main()
{
pre();
memset(dp,-1,sizeof(dp));
while(scanf("%lld %lld",&lo,&hi))
{
scanf("%d",&x);
if(!(x+lo+hi))break;
printf("%lld\n",getsum3(hi)-getsum3(lo-1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: