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

Array Rotation and Queries

Back to problem

Editorial

Create two distinct vertices vvv and −v-v−v for every integer vvv from 111 to NNN. Also create two sentinel vertices LLL and RRR for the left and right ends.

For the current sequence [a1,a2,⋯ ,aN][a_1,a_2,\cdots,a_N][a1​,a2​,⋯,aN​, store the following undirected edges.

  • Connect LLL with −a1-a_1−a1​.
  • For every 1≤i<N1\leq i<N1≤i<N, connect aia_i with .

Every vertex has degree exactly 111, so its unique neighbor can be stored in an array mate⁡\operatorname{mate}mate.

If two consecutive sequence values are u,vu,vu,v, their adjacency is represented by the edge {u,−v}\{u,-v\}{u,−v}. After both reversing and negating that part, the corresponding consecutive values become −v,−u-v,-u−v,−u. Their edge is {−v,u}\{-v,u\}, which is the same undirected edge. Therefore, every edge strictly inside the queried interval remains unchanged.

Let the query endpoints be x,yx,yx,y, and define

ℓ=mate⁡(−x),r=mate⁡(y).\ell=\operatorname{mate}(-x),\qquad r=\operatorname{mate}(y).ℓ=mate(−x),r=mate(y).

Before the query, the edges {−x,ℓ}\{-x,\ell\}{−x,ℓ} and {y,r}\{y,r\}{y,r} exist. Remove them and add

{ℓ,y},{−x,r}.\{\ell,y\},\qquad \{-x,r\}.{ℓ,y},{−x,r}.

These two changes exactly replace the first value xxx by −y-y−y and the last value yyy by −x-x−x. Thus, each query changes only four array entries.

To reconstruct the final sequence, start at LLL. Since mate⁡(L)=−a1\operatorname{mate}(L)=-a_1mate(L)=−a1​, the first value is −mate⁡(L)-\operatorname{mate}(L)−mate(L. If the current value is and , the next value is .

Initialization and reconstruction take O(N)O(N)O(N) time, while each query takes O(1)O(1)O(1) time. The total time complexity is O(N+Q)O(N+Q)O(N+Q) and the memory complexity is O(N)O(N).

Solution written by GPT5.6

]
ai​
−ai+1-a_{i+1}−ai+1​
  • Connect aNa_NaN​ with RRR.
  • {
    −
    v
    ,
    u
    }
    )
    vvv
    mate⁡(v)≠R\operatorname{mate}(v)\neq Rmate(v)=R
    −mate⁡(v)-\operatorname{mate}(v)−mate(v)
    O
    (
    N
    )