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

Three-Dimensional Ladder Game

Back to problem

Editorial

For each destination iii, let pip_ipi​ be the zero-based index of its starting pole. Initially set di=i−pid_i=i-p_idi​=i−pi​. Unwrap the circle into an infinite line; adding a multiple of NNN to did_idi​ represents another lift of the same destination.

If du−dv>Nd_u-d_v>Ndu​−dv​>N, subtract NNN from and add to . This preserves the sum of displacements and does not increase the number of necessary crossings. Repeat until the difference between the maximum and minimum displacements is at most .

Define xi=pi+dix_i=p_i+d_ixi​=pi​+di​. For , the minimum number of crossings between these two paths is

∣⌊xi−xj−1N⌋+[pi<pj]∣.\left|\left\lfloor\frac{x_i-x_j-1}{N}\right\rfloor+[p_i<p_j]\right|.​⌊Nx

The bracket equals 111 when its condition holds and 000 otherwise. Sum this expression over all i<ji<ji<j. Use mathematical floor division, not integer division truncated toward zero, for negative numerators.

When choosing the maximum and minimum each time, no index needs to be adjusted twice, so there are O(N)O(N)O(N) adjustments. Each adjustment takes O(N)O(N)O(N) time and the pair sum takes O(N2)O(N^2)O(N2) time. Total time is O(N2 with auxiliary space.

Solution written by GPT6

dud_u
du​
NNN
dvd_vdv​
NNN
i<ji<j
i<j
i
​
−
xj​
−
1
​
⌋
+
[
pi​
<
pj​
]
​
.
)O(N^2)
O(N2)
O(N)O(N)O(N)