您的位置:首页 > 其它

Codecraft-18 and Codeforces Round #458(C)-Travelling Salesman and Special Numbers(数位DP)

2018-02-01 21:40 375 查看
C. Travelling Salesman and Special Numbers

time limit per test
1 second

memory limit per test
256 megabytes

input
standard input

output
standard output

The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and
reduce it to the number of bits set to 1 in the binary representation of x.
For example for number 13 it's true that 1310 = 11012,
so it has 3 bits set and 13 will
be reduced to 3 in one operation.

He calls a number special if the minimum number of operations to reduce it to 1 is k.

He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about
to reach his destination!

Since the answer can be large, output it modulo 109 + 7.

Input

The first line contains integer n (1 ≤ n < 21000).

The second line contains integer k (0 ≤ k ≤ 1000).

Note that n is given in its binary representation without any leading zeros.

Output

Output a single integer — the number of special numbers not greater than n, modulo 109 + 7.

Examples

input
110
2


output
3


input
111111011
2


output
169


Note

In the first sample, the three special numbers are 3, 5 and 6.
They get reduced to 2 in one operation (since there are two set bits in each of3, 5 and 6)
and then to 1 in one more operation (since there is only one set bit in 2).

题意:给你一个n,然后问你1到n中有多少个数按照题意操作k次正好编变成1

操作规则:对于当前数,将其转化为二进制看有多少个1,则该数变成1的个数之和,算操作一次。

题解:n有2的1000次方这么大,但是我们知道在第一次操作后一定变成了一个1000以内的数,因此我们可以预处理出来前1000个数变成1要操作多少次,然后对n的二进制表示进行数位dp即可。设dp[x][y]:二进制表示为x位,1的个数为y以内满足题目的个数。

#include<stdio.h>
#include<string.h>
#define mod 1000000007
char s[1005];
int f[1005],digit[1005],dp[1005][1005],k,len;
void init()
{
memset(dp,-1,sizeof(dp));
for(int i=2;i<=1000;i++)
{
int tmp=i,num=0;
while(tmp)
num+=tmp%2,tmp/=2;
f[i]=f[num]+1;
}
}
int dfs(int pos,int num,int lim)
{
if(pos==0) return (f[num]==k-1);
if(!lim && dp[pos][num]!=-1)
return dp[pos][num];
int res=0,sum=lim?digit[pos]:1;
for(int i=0;i<=sum;i++)
{
int tmp=num;
if(i>0) tmp++;
res+=dfs(pos-1,tmp,lim && i==sum);
res%=mod;
}
return lim?res:dp[pos][num]=res;
}
int main(void)
{
init();
scanf("%s%d",s+1,&k);
int len=strlen(s+1);
for(int i=1;i<=len;i++)
digit[i]=s[i]-'0';
int l=1,r=len;
while(l<=r)
{
int tmp=digit[l];
digit[l]=digit[r];
digit[r]=tmp;
l++;r--;
}
if(k==0)
{
printf("1\n");
return 0;
}
if(k==1)
{
printf("%d\n",len-1);
return 0;
}
printf("%d\n",dfs(len,0,1));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: