Codeforces 914C Travelling Salesman and Special Numbers(数位dp)

    科技2022-07-10  201

    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 of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2).

    题意:

    求不大于n的正整数并且恰好经过k次变化后成1的数的个数,变化规则为:x -> (x的二进制的1个数)

    做法

    二进制数位DP,将高位中已枚举的1的个数作为记忆化状态(最多不超过1000个1)。在递归终点的时候判断该数的操作次数是否等于k。求操作次数的话,可以预处理一下。注意,不是预处理 【1,2^1000】(时间空间都不允许),而是预处理[1,1000]以内的数,相当于是 【1,2^1000】的数先做了一次操作之后的数,这样在最后计算答案的时候 +1就是实际操作次数。需要注意的是0和1 两个数需要特别处理一下。

    #include<bits/stdc++.h> using namespace std; typedef long long LL; const LL mod = 1e9 + 7; int f(int x)//二进制 表示下 1 的个数 { int res = 0; while (x) { res += x & 1; x >>= 1; } return res; } int get_OP_cnt(int x)// x->f(x) until x==1 操作次数 { if (x == 1)return 0; return 1 + get_OP_cnt(f(x)); } int OP_times[1234]; inline void init() { for (int i = 1; i < 1234; i++) { OP_times[i] = get_OP_cnt(i); } } int num[1234]; LL dp[1001][2][1001]; LL dfs(int pos,bool limit,bool zero,int bin_one,int k,int pre) { if (pos == 0) { if (pre == 1)return k == 0; return !zero && OP_times[bin_one] + 1 == k; } if (~dp[pos][limit][bin_one])return dp[pos][limit][bin_one]; LL res = 0; int up = limit ? num[pos] : 1; for (int i = 0; i <= up; i++) { res += dfs(pos - 1, limit && i == up, zero && i == 0, bin_one + (i == 1), k,zero ?i:-1); res %= mod; } dp[pos][limit][bin_one] = res; return res; } char s[1234]; int main() { #ifdef DEBUG freopen("C:\\Users\\Admin\\source\\repos\\DEBUG\\IO\\1.in", "r", stdin); #endif init(); memset(dp, -1, sizeof(dp)); int k; scanf("%s%d", s+1,&k); int len = strlen(s + 1); for (int i = 1; i <= len; i++) { num[len - i + 1] = s[i] - '0'; } LL ans = dfs(len, true, true, 0, k, -1); printf("%lld\n", ans); return 0; }
    Processed: 0.026, SQL: 8