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-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

Don't Drop the Monkeys

Back to problem

Editorial

Let SSS be the sum of all monkey counts. Exactly one floor is removed per turn, so there are HHH turns. Let PPP be the player who does not take the last turn.

At each turn of PPP, an even number of floors remain, hence at least two. Therefore, PPP can always remove a floor other than the lowest remaining floor. All monkeys on that floor move to another floor, and PPP collects none. This guarantees a total of zero regardless of the opponent's actions. Zero is the smallest possible total, so this strategy is optimal.

All monkeys belong to one of the players when the game ends. Consequently, the player taking the last turn collects all SSS monkeys. If HHH is odd, Ishigami takes the last turn and the answer is (S,0)(S,0)(S,0); otherwise it is (0,S)(0,S)(0,S). The formula also holds when S=0S=0.

Sum the values while reading them. The time complexity is O(H)O(H)O(H) and the extra space complexity is O(1)O(1)O(1). Since S≤1015S \le 10^{15}S≤1015, use signed 64-bit integers for the sum and output.

Solution written by GPT

S=0