题解:P17189 [ICPC 2017 Hong Kong R] Count the Even Integers

· · 题解

问题定义

给定正整数 n,求满足。

0 \le j \le i \le n,\quad \binom{i}{j} \equiv 0 \pmod{2}

的有序正整数对 (i,j) 的个数。

Lucas 定理的转化

把 i 和 j 写成二进制:

i = (a_k a_{k-1} \dots a_0)_2,\quad j = (b_k b_{k-1} \dots b_0)_2

由 Lucas 定理,在模 2 意义下:

\binom{i}{j} \equiv \prod_{t=0}^{k} \binom{a_t}{b_t} \pmod{2}.

当 a_t,b_t\in\{0,1\} 时,仅当某个位置上 a_t=0 且 b_t=1 时 \binom{a_t}{b_t}=0。

因此:

\binom{i}{j} \equiv 0 \pmod{2} \iff \exists t,\ a_t=0 \land b_t=1.

此问题可用数位 DP 在二进制下直接统计。

具体实现

考虑设计状态:

设 dp_{cur,dif,lima,limb} 表示当前处理到了第 cur 位,j 是否和 i 出现了差异,i 是否顶着上限 n, j 是否顶着上限 n。

直接记搜实现即可。

::::warning[警告] 题目十分毒瘤,数据范围极大,long long 存不下。

于是就有两种方式。

:::success[我会实现高精度] 几乎所有变量都要用高精度,因为 dp 数组中的最大值接近 n^2 是 10^{100} 量级的。 :::

:::success[我会用 pyhton 或者 java] 自带高精度,直接写即可。 ::: ::::

:::info[代码( python )]

def dec_to_bin(s):
    if s=="0": return "0"
    bin=""
    while s!="0":
        rem=0
        q=""
        for i in range(len(s)):
            cur=rem*10+int(s[i])
            d=cur//2
            rem=cur%2
            if q!="" or d>0:
                q+=str(d)
        bin=str(rem)+bin
        s=q if q!="" else "0"
    return bin
def dfs(cur,can,dif,lia,lib,lima,limb,dp,k):
    if cur==0:
        return 1 if can else 0
    if dp[cur][can][dif][lia][lib]!=-1:
        return dp[cur][can][dif][lia][lib]
    up1=lima[cur] if lia else k-1
    up2=limb[cur] if lib else k-1
    res=0
    for i in range(up1+1):
        for j in range(up2+1):
            if (not dif) and j>i:
                continue
            res+=dfs(cur-1,can or (i<j),dif or (i!=j),lia and (i==up1),lib and (j==up2),lima,limb,dp,k)
    dp[cur][can][dif][lia][lib]=res
    return res
def solve():
    n=input().strip()
    bin=dec_to_bin(n)
    length=len(bin)
    lima=[0]*(length+1)
    limb=[0]*(length+1)
    for i in range(1,length+1):
        lima[i]=int(bin[length-i])
        limb[i]=int(bin[length-i])
    dp=[[[[[-1]*2 for _ in range(2)] for _ in range(2)] for _ in range(2)] for _ in range(length+1)]
    ans=dfs(length,0,0,1,1,lima,limb,dp,2)
    print(ans)

:::

可以做一下这个题的扩展版,思路是一样的:P6669 [清华集训 2016] 组合数问题。

蒟蒻第一次写题解,求过。