题目链接:http://codeforces.com/contest/914/problem/C
题意:有一个操作,可以使一个数字变成另一个数字,这个数字就是原数字二进制形式中1的个数。比如13的二进制位1101,有3个1,那么经过一次操作就变成了3,直到变为1为止,所经过的步数就是最小操作步数。
现在问1~n中有多少个数最小操作步数为k。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=1005;
const int MOD=1e9+7;
typedef long long LL;
char str[maxn+5];
LL a[maxn+5];//记录1-1000的数变为1所需要的次数
LL C[maxn+5][maxn+5];//排列组合
LL cal(LL x)//计算一个数的二进制中1的位数和
{
LL sum=0;
while(x>0)
{
if(x%2==1)
sum++;
x/=2;
}
return sum;
}
void init1()//预处理a[i]
{
for(LL i=1;i<=1005;i++)
{
LL t=i;
while(t!=1)
{
t=cal(t);
a[i]++;
}
}
}
void init2()//排列组合预处理
{
for(int i=0;i<=maxn;i++)
{
C[i][0]=1;
C[i][i]=1;
}
for(int i=1;i<=maxn;i++)
{
for(int j=1;j<i;j++)
{
C[i][j]=(C[i-1][j]+C[i-1][j-1])%MOD;
}
}
}
LL dfs(char str[],int x,int now,int len)//递归计算排列组合的位数
{
if(now>=len)
return 0;
LL sum=0;
if(str[now]=='1')
{
sum=C[len-now-1][x];
if(x==1)
return sum=(sum+1)%MOD;
return (sum+dfs(str,x-1,now+1,len))%MOD;
}
else
return (sum+dfs(str,x,now+1,len))%MOD;
}
int main()
{
init1();
init2();
LL ans,x,len;
cin>>str>>x;
len=strlen(str);
if(x==0)//0的情况特殊处理
{
puts("1");
return 0;
}
ans=0;
for(int i=1;i<=len;i++)
{
if(a[i]==x-1)//如果a[i]==x-1,说明应该排列i位
{
ans+=dfs(str,i,0,len)%MOD;
ans%=MOD;
}
}
if(x==1)//001本身要除去
ans--;
cout << ans << endl;
return 0;
}
本文解析了CodeForces上的一道题目C,该题要求找出1到n之间,通过特定操作达到1所需的最少步骤为k的所有数字数量。文中提供了完整的C++代码实现,包括预处理、递归计算等关键步骤。
464

被折叠的 条评论
为什么被折叠?



