DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

흑백 트리

Back to problem

Editorial

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)