DOJ logoDOJ
题目
最近添加的题目收藏的题目Workbooks
分类DLC比赛小组团队讨论区
排名
解题数量排行榜连续解题排名DOJ Power 排行榜
评测状态
征题登录注册
DOJ logoDOJ

支持 OI 子任务计分、Elo 等级分和 Discord 认证的社区在线评测系统。

题目
题目列表分类
社区
比赛排名讨论区公告举办外部比赛指南
账号
登录注册评测状态
政策
服务条款DLC 使用规则隐私政策API 文档语言运行环境比赛排名奖励评级与表现
© 2026 DOJ
保留所有权利
题解

흑백 트리

返回题目

题解

Assign weight +1+1+1 to each black vertex and weight −1-1−1 to each white vertex. Then a black-white component is exactly a connected vertex set whose total weight is 000.

Root the tree at vertex 111. Every connected vertex set SSS has a unique vertex closest to the root. Call it the top of SSS.

Let Fv(x)F_v(x)Fv​(x) be the generating function of connected vertex sets whose top is vvv. Then,

Fv(x)=xwv∏c(1+Fc(x))F_v(x)=x^{w_v}\prod_c(1+F_c(x))Fv​(x)=xwv​

The answer is the sum of the constant coefficients of Fv(x)F_v(x)Fv​(x) over all vertices vvv.

For N≤200000N \le 200000N≤200000, merging child polynomials one by one in O(N2)O(N^2)O(N2) is not enough. Choose one heavy child hhh and define Av(x)=xwv∏c≠. Then . Along a heavy path, each vertex is an affine transform . Compose these transforms in a balanced way and use NTT for polynomial multiplication. Store for each interval so that the top DP is and the interval contribution is . This gives an -style solution.

∏c​
(
1
+
Fc​(x))
h(1+Fc(x))A_v(x)=x^{w_v}\prod_{c\ne h}(1+F_c(x))
Av​(x)=xwv​∏c=h​(1+Fc​(x))
Fv(x)=Av(x)(1+Fh(x))F_v(x)=A_v(x)(1+F_h(x))Fv​(x)=Av​(x)(1+Fh​(x))
Y↦Av+AvYY \mapsto A_v+A_vYY↦Av​+Av​Y
P,Q,M,CP,Q,M,CP,Q,M,C
P+QYP+QYP+QY
C+[x0](MY)C+[x^0](MY)C+[x0](MY)
O(Nlog⁡2N)O(N\log^2 N)O(Nlog2N)