跳到正文

题解

ABC462G

_constexpr_int_约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年6月14日
更新
2026年6月23日
篇幅
约 5 分钟

版本

  1. v1当前

本来切完 ABC 准备看 D 的,结果听说 G 比较水,就先做了 G。

记颜色 cc 在初始球中出现的次数为 fcf_c,在目标序列 GG 中出现的次数为 mcm_c。

记随机排列 π\pi 表示第 kk 次抽出的球的编号,则总得分为 00 可等价于

∀k, Cπ(k)≠Gk\forall k,\ C_{\pi(k)} \ne G_k

考虑直接容斥,设 AkA_k 表示事件第 kk 次抽到的球颜色等于 GkG_k,则

Pr⁡(无事件发生)=∑S⊆{1,2,…,n}(−1)∣S∣Pr⁡(⋀k∈SAk)\Pr(\text{无事件发生})=\sum_{S \subseteq \{1,2,\dots,n\}} (-1)^{|S|} \Pr\left(\bigwedge_{k \in S} A_k\right)

其中 Pr⁡(⋀k∈SAk)\Pr\left(\bigwedge_{k \in S} A_k\right) 是强制所有 k∈Sk \in S 的位置上抽出的颜色必须等于 GkG_k 的概率。

对于固定的 SS,满足所有 k∈Sk \in S 上颜色等于 GkG_k 的排列数目为:

  • 对于每个颜色 cc,从 fcf_c 个同色球中选出 tct_c 个,并分配到 SS 中颜色为 cc 的位置上,这些球之间有序,即共有 tc!t_c! 种方式;
  • 剩下的 n−∣S∣n-|S| 个位置以及未被选中的 n−∣S∣n-|S| 个球,可以任意排列,即共有 (n−∣S∣)!(n-|S|)! 种方式。

因此,满足所有强制条件的总数为

∏c(fctc)⋅tc!⋅(n−∣S∣)!=∏cfc!(fc−tc)!⋅(n−∣S∣)!\prod_c \binom{f_c}{t_c} \cdot t_c! \cdot (n-|S|)! = \prod_c \frac{f_c!}{(f_c-t_c)!} \cdot (n-|S|)!

于是,对于给定的 SS,该事件的概率为

Pr⁡(⋀k∈SAk)=∏cfc!(fc−tc)!⋅(n−∣S∣)!n!\Pr\left(\bigwedge_{k \in S} A_k\right)=\frac{\displaystyle \prod_c \frac{f_c!}{(f_c-t_c)!} \cdot (n-|S|)!}{n!}

设 r=∣S∣r=|S|,则容斥和式可以按 rr 分组,而不同的 SS 对应的 ∏fc!(fc−tc)!\displaystyle \prod \frac{f_c!}{(f_c-t_c)!} 不仅仅依赖于 rr,还依赖于每个颜色上的 tct_c 的分布,我们需要对所有满足 ∑ctc=r\sum_c t_c=r 且 0≤tc≤min⁡(fc,mc)0 \le t_c \le \min(f_c,m_c) 的向量 (tc)(t_c) 求和,每个向量的贡献为

(−1)r⋅(n−r)!n!⋅∏cfc!(fc−tc)!⋅#{S∣tc=#{k∈S:Gk=c}}(-1)^r \cdot \frac{(n-r)!}{n!} \cdot \prod_c \frac{f_c!}{(f_c-t_c)!} \cdot \#\{ S \mid t_c = \#\{k \in S : G_k = c\} \}

其中 #{S}\#\{S\} 是选择位置集合使得每个颜色 cc 恰好出现 tct_c 次的方案数。由于 GG 已知,所以从这些位置中选出 tct_c 个的方案数为 (mctc)\binom{m_c}{t_c},而不同的颜色相互独立,从而方案数为

∏c(mctc)\prod_c \binom{m_c}{t_c}

因此容斥总和为

∑tc≥0∑tc=r(−1)r(n−r)!n!∏cfc!(fc−tc)!(mctc)\sum_{\substack{t_c \ge 0 \\ \sum t_c=r}} (-1)^r \frac{(n-r)!}{n!} \prod_c \frac{f_c!}{(f_c-t_c)!} \binom{m_c}{t_c}

将 rr 的求和提到外面:

ans=1n!∑r=0n(n−r)!⋅∑tc∑tc=r∏cfc!(fc−tc)!(mctc)\text{ans} = \frac{1}{n!} \sum_{r=0}^n (n-r)! \cdot \sum_{\substack{t_c \\ \sum t_c=r}} \prod_c \frac{f_c!}{(f_c-t_c)!} \binom{m_c}{t_c}

记

Pc(x)=∑t=0min⁡(fc,mc)(−1)tfc!(fc−t)!(mct)⋅xtP_c(x)=\sum_{t=0}^{\min(f_c,m_c)} (-1)^t \frac{f_c!}{(f_c-t)!} \binom{m_c}{t} \cdot x^t

则多项式乘积为

P(x)=∏cPc(x)=∑rarxrP(x)=\prod_c P_c(x) = \sum_{r} a_r x^r

其中

ar=∑∑tc=r∏c(−1)tcfc!(fc−tc)!(mctc)a_r=\sum_{\sum t_c=r} \prod_c (-1)^{t_c} \frac{f_c!}{(f_c-t_c)!} \binom{m_c}{t_c}

于是答案为

1n!∑r=0n(n−r)!⋅ar\frac{1}{n!} \sum_{r=0}^n (n-r)! \cdot a_r

注意到

fc!(fc−t)!=fct‾\frac{f_c!}{(f_c-t)!} = f_c^{\underline t}

组合数

(mct)=mc!t!(mc−t)!\binom{m_c}{t} = \frac{m_c!}{t!(m_c-t)!}

所以

Pc(x)=∑t(−1)t⋅fct‾⋅(mct)⋅xtP_c(x)=\sum_t (-1)^t \cdot f_c^{\underline t} \cdot \binom{m_c}{t} \cdot x^t

由于颜色总数最多为 nn,对于每个出现过的颜色,有

deg⁡(Pc(x))≤min⁡(fc,mc)\deg(P_c(x)) \le \min(f_c,m_c)

可以用 NTT 直接优化到 O(nlog⁡2n)O(n \log^2 n),且模数为 998244353998244353,原根为 33,NTT 即可。

Submission。

原文