DOJ logoDOJ
Problems
Recently added problemsSaved problemsWorkbooks
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 account linking.

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

All Falls Down

Back to problem

Editorial

Define an integer r(v)r(v)r(v) for each vertex vvv as follows.

  • If vvv is a leaf, then r(v)=0r(v)=0r(v)=0.
  • If a child ccc with even r(c)r(c)r(c) exists, take the minimum such value and add 111.
  • Otherwise, take the maximum r(c)r(c)r(c) among all children and add 111.

These values can be computed from the leaves upward. If r(v)r(v)r(v) is positive and even, all children have odd values and their maximum is r(v)−1r(v)-1r(v)−1. If r(v)r(v)r(v) is odd, there is an even-valued child with value r(v)−1r(v)-1, and every even-valued child has value at least .

When the tokens are at u,vu,vu,v, the player to move loses exactly when min⁡(r(u),r(v))\min(r(u),r(v))min(r(u),r(v)) is even. Prove this by induction as both tokens move downward.

Suppose the minimum is an even value kkk. If k=0k=0k=0, one token has no legal move. If k>0k>0k>0, every child of a token with value kkk has an odd value smaller than kkk. An even-valued child of the other token has value at least ; if that child is odd-valued instead, the minimum of the two child values is still odd. Thus every move reaches a position winning for the opponent.

Now suppose the minimum kkk is odd. A token with value kkk can move to an even-valued child with value k−1k-1k−1. If the other token has an odd value, it can move to an even-valued child with value at least k−1k-1k−1. If it has an even value, it can move to an odd-valued child with value at least kk. Hence a move to a position with an even minimum always exists.

Bob moves first after Alice chooses a pair. Therefore we count pairs with an even minimum of their rrr values. Count vertices by rrr value and process these values in decreasing order. At an even value, add the pairs within its frequency group and the pairs between this group and all larger values. Store the answer in a 646464-bit integer.

The time and space complexity are both O(N)O(N)O(N) per case.

Solution written by GPT6

r(v)−
1
r(v)−1r(v)-1r(v)−1
kkk
k