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

Binary Tree Queries

Back to problem

Editorial

If a vertex vvv is chosen as the root, every neighbor of vvv becomes a child of vvv. Therefore, a vertex of degree at least 333 cannot be chosen as the root of a binary tree.

Since the tree remains binary for every possible root, every vertex has degree at most 222. A connected tree whose vertices all have degree at most 222 is a path.

List the vertices in order from one endpoint of this path. Let PvP_vPv​ be the position of vertex vvv. Let RRR be the position of the current root, and let PPP be the position of the queried vertex ii.

Build a Fenwick tree over this path order. Let S(x)S(x)S(x) denote the number of white vertices among the first xxx positions.

If P<RP<RP<R, the root lies to the right of iii. The subtree of iii is the interval [1,P][1,P][1,P], and the path from iii to the root is .

a=S(P),b=S(R)−S(P−1)a=S(P),\qquad b=S(R)-S(P-1)a=S(P),b=S(R)−S(P−1)

If P>RP>RP>R, the root lies to the left of iii. The subtree of iii is the interval [P,N][P,N][P,N], and the path from iii to the root is .

a=S(N)−S(P−1),b=S(P)−S(R−1)a=S(N)-S(P-1),\qquad b=S(P)-S(R-1)a=S(N)−S(P−1),b=S(P)−

If P=RP=RP=R, vertex iii is the current root. Its subtree is the entire tree, while the path contains only iii.

a=S(N),b=Cia=S(N),\qquad b=C_ia=S(N),b=Ci​

A type 1 query only changes the stored root position. A type 2 query adds 111 or −1-1−1 at one Fenwick tree position. A type 3 query uses the formulas above.

Finding the path order takes O(N)O(N)O(N) time. Building the Fenwick tree takes O(Nlog⁡N)O(N\log N)O(NlogN) time. Every query takes O(log⁡N)O(\log N)O(logN) time, so the total time complexity is O((N and the memory complexity is .

Solution written by GPT5.6

i
[P,R][P,R][P,R]
[R,P][R,P][R,P]
S(R−
1)
+Q)log⁡N)O((N+Q)\log N)
O((N+Q)logN)
O(N)O(N)O(N)