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

Half Shuffle

Back to problem

Editorial

Let M={i∣Pi≠i}M=\{i\mid P_i\ne i\}M={i∣Pi​=i} be the set of misplaced positions and let m=∣M∣m=|M|m=∣M∣.

If m=0m=0m=0, the answer is 000.

If 1≤m≤N1\le m\le N1≤m≤N, the answer is 111. Choose every misplaced position and add arbitrary fixed positions until exactly NNN positions are chosen; one rearrangement can sort them all.

Now assume m>Nm>Nm>N. Let AAA and BBB be the position sets chosen in two rearrangements. Since ∣A∣=∣B∣=N|A|=|B|=N∣A∣=∣B∣=,

∣A∩B∣=∣{1,⋯ ,2N}∖(A∪B)∣.|A\cap B|=|\{1,\cdots,2N\}\setminus(A\cup B)|.∣A∩B∣=∣{1,⋯,2N}∖(A∪B)∣.

Every position outside A∪BA\cup BA∪B is never touched, so it must already be a fixed point.

If at least one fixed point exists, the answer is 222. One rearrangement is impossible because m>Nm>Nm>N, while a fixed point can be kept outside both chosen sets so that the permutation can always be finished in two rearrangements.

Now suppose there is no fixed point. Then no position can lie outside A∪BA\cup BA∪B, so the equality above forces A∩B=∅A\cap B=\varnothingA∩B=∅. Thus AAA and BBB partition all positions. Every position in is touched only by the first rearrangement, so all of them must already be correct after that rearrangement.

Decompose the permutation into cycles. If AAA contains only part of a cycle, at least one position in that part needs a value that remains in BBB. Therefore AAA must be a union of whole cycles. Conversely, if some cycle lengths sum to exactly NNN, those cycles can be sorted in the first rearrangement and all remaining cycles in the second.

Hence, when there is no fixed point, two rearrangements are possible if and only if some subset of the cycle lengths sums to exactly NNN. This is a standard subset-sum DP and can be checked in O(N2)O(N^2)O(N2) time.

If such a subset exists, the answer is 222; otherwise it is 333. Two rearrangements are impossible by the condition above, while one preliminary rearrangement can create a fixed point, after which at most two more rearrangements are sufficient.

Therefore the answer is always one of 0,1,2,30,1,2,30,1,2,3. The time complexity is O(N2)O(N^2)O(N2) per test case and the memory complexity is O(N)O(N)O(N).

Solution written by GPT5.6

N
AA
A