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

Mountain Climbing Game

Back to problem

Editorial

Let prp_rpr​ be the nearest position left of rrr with height greater than ArA_rAr​, or 000 if none exists. Dadas wins under exactly these conditions:

  • If Al<ArA_l<A_rAl​<Ar​, some internal height exceeds AlA_lAl.

Process right endpoints rrr from left to right. A Fenwick tree stores earlier heights; let F(v)F(v)F(v) count those at most vvv. Maintain a stack of indices with decreasing heights. Pop all heights below ArA_rAr​, recording their number . The remaining top, if any, is .

Combining both types, the contribution of rrr is

F(hr−1)−cr,hr={Aprpr>0,Arpr=0.F(h_r-1)-c_r,\qquad h_r=\begin{cases}A_{p_r}&p_r>0,\\A_r&p_r=0.\end{cases}F(hr​−1)−

Add it to the answer, insert ArA_rAr​ into the Fenwick tree, and push rrr onto the stack. Time complexity is O(Nlog⁡N)O(N\log N)O(NlogN) and space complexity is O(N)O(N).

Proof

If Al<ArA_l<A_rAl​<Ar​, Dadas can move to the rightmost internal position higher than AlA_lA. Every remaining internal height is below , so Ttas cannot move. If no such position exists, Dadas cannot move.

​
  • If Al>ArA_l>A_rAl​>Ar​, then l<prl<p_rl<pr​ and Al<AprA_l<A_{p_r}Al​<Apr​​.
  • crc_r
    cr​
    prp_rpr​
    cr​
    ,
    hr​
    =
    {Apr​​Ar​​pr​>0,pr​=0.​
    O(N)
    l
    ​
    AlA_lAl​

    If Al>ArA_l>A_rAl​>Ar​, l<prl<p_rl<pr​, and Al<AprA_l<A_{p_r}Al​<Apr​​, Dadas can move to prp_rpr​ and win immediately. If pr≤lp_r\leq lpr​≤l, he has no move. Otherwise, pr>lp_r>lpr​>l and Apr<AlA_{p_r}<A_lApr​​<Al​, so any legal first move reaches some i<pri<p_ri<pr​. Ttas replies at the leftmost position after iii higher than ArA_rAr​, leaving no legal move for Dadas.

    There are F(Ar−1)F(A_r-1)F(Ar​−1) candidates with Al<ArA_l<A_rAl​<Ar​. Such a pair loses precisely when rrr is the first higher position to the right of lll. These are exactly the indices just popped, so this type contributes F(Ar−1)−crF(A_r-1)-c_rF(Ar​−1)−cr​ wins.

    The other type requires Ar<Al<AprA_r<A_l<A_{p_r}Ar​<Al​<Apr​​. Every height between prp_rpr​ and rrr is below ArA_rAr​, so an earlier height in this value range automatically lies left of prp_rpr​. If pr>0p_r>0pr​>0, add F(Apr−1)−F(Ar)F(A_{p_r}-1)-F(A_r)F(Apr​​−1)−F(A. Since ArA_rAr​ has not been inserted, F(Ar)=F(Ar−1)F(A_r)=F(A_r-1)F(Ar​)=F(Ar​−1), giving the stated formula.

    r
    ​
    )