|
| 1 | +const ll = BigInt, |
| 2 | + mod = ll(1e9 + 7), |
| 3 | + N = 1e4 + 15 |
| 4 | +let fact = Array(N).fill(0), |
| 5 | + ifact = Array(N).fill(0), |
| 6 | + inv = Array(N).fill(0) |
| 7 | +const hcomb = (p, q) => (p == 0 && q == 0 ? 1 : comb(p + q - 1, q)) |
| 8 | +const comb_init = () => { |
| 9 | + fact[0] = ifact[0] = inv[1] = 1n // factorial, inverse factorial |
| 10 | + for (let i = 2; i < N; i++) |
| 11 | + inv[i] = ((mod - mod / ll(i)) * inv[mod % ll(i)]) % mod |
| 12 | + for (let i = 1; i < N; i++) { |
| 13 | + fact[i] = (fact[i - 1] * ll(i)) % mod |
| 14 | + ifact[i] = (ifact[i - 1] * inv[i]) % mod |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +// combination mod pick k from n |
| 19 | +const comb = (n, k) => { |
| 20 | + if (n < k || k < 0) return 0 |
| 21 | + return (((fact[n] * ifact[k]) % mod) * ifact[n - k]) % mod |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} s |
| 26 | + * @param {number} k |
| 27 | + * @return {number} |
| 28 | + */ |
| 29 | +var countKReducibleNumbers = function (s, k) { |
| 30 | + let dp = new Array(1000).fill(0) |
| 31 | + for (let i = 2; i < 1000; i++) { |
| 32 | + dp[i] = dp[bitCnt(i)] + 1 |
| 33 | + } |
| 34 | + let c1 = 0 |
| 35 | + let n = s.length |
| 36 | + let res = 0n |
| 37 | + comb_init() |
| 38 | + for (let i = 0; i < n; i++) { |
| 39 | + if (s[i] === "1") { |
| 40 | + for (let c2 = 0; c2 < n - i; c2++) { |
| 41 | + if (c1 + c2 > 0 && dp[c1 + c2] + 1 <= k) { |
| 42 | + res = res + comb(n - i - 1, c2) |
| 43 | + } |
| 44 | + } |
| 45 | + c1++ |
| 46 | + } |
| 47 | + } |
| 48 | + return Number(res % mod) |
| 49 | + |
| 50 | + function bitCnt(num) { |
| 51 | + let cnt = 0 |
| 52 | + while (num) { |
| 53 | + cnt += num & 1 |
| 54 | + num >>= 1 |
| 55 | + } |
| 56 | + return cnt |
| 57 | + } |
| 58 | +} |
0 commit comments