C. Travelling Salesman and Special Numbers

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值