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

Grid Sort

Back to problem

Editorial

Complete the columns from left to right. When processing column iii, consider its two target values, iii and N+iN+iN+i, together. Never touch an already completed column.

  • If the two targets are in the same row, vertically swap the target that is in the wrong row at its current column. Both targets are now in their correct rows; move each left to column iii using horizontal swaps.
  • If the targets are in different rows, move each left to column iii within its current row. If their rows are reversed, finish with one vertical swap in column iii.

Store the current position of every value and update it after each swap. Record the swaps, then print their count and the recorded sequence. Both the time complexity and the space complexity, including the recorded swaps, are O(N2)O(N^2)O(N2).

Proof

Before column iii is processed, both targets are in columns iii through NNN. All swaps remain within this region. The targets are placed in different rows before being moved left, so moving either target cannot displace the other. Thus column iii is completed correctly without disturbing earlier columns.

Let m=N−i+1m=N-i+1m= be the number of remaining columns. Each target needs at most horizontal swaps, and either case uses at most one vertical swap. The total number of swaps is therefore at most

N
−
i+
1
m−1m-1m−1
∑m=1N(2(m−1)+1)=N2,\sum_{m=1}^{N}\bigl(2(m-1)+1\bigr)=N^2,m=1∑N​(2(m−1)+1)=N2,

which meets the full-score requirement.