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

Permutation Flip

Back to problem

Editorial

Let FFF be the number of fixed points in the initial permutation.

Suppose we reverse the segment [l,r][l,r][l,r] and set s=l+rs=l+rs=l+r. The value originally at position jjj inside the segment moves to position s−js-js−j. Hence it becomes a fixed point after the reversal if and only if Aj=s−jA_j=s-jAj​=s−j, or equivalently j+Aj=sj+A_j=sj+Aj​=s.

Thus the number of fixed points after reversing [l,r][l,r][l,r] is

F−#{j:l≤j≤r, Aj=j}+#{j:l≤j≤r, j+Aj=l+r}.F-\#\{j:l \leq j \leq r,\ A_j=j\}+\#\{j:l \leq j \leq r,\ j+A_j=l+r\}.F−#{j:l≤j≤r, A

We need to maximize the difference between the subtracted term and the added term.

For a fixed value s=l+rs=l+rs=l+r, the possible range of lll is

max⁡(1,s−N)≤l≤⌊s−12⌋.\max(1,s-N) \leq l \leq \left\lfloor\frac{s-1}{2}\right\rfloor.max(1,s−N)≤l≤⌊2s−

For a position jjj satisfying j+Aj=sj+A_j=sj+Aj​=s, the condition that jjj lies inside [l, is equivalent to . For every , store all values with and sort them. Then the number of newly created fixed points for a given can be found by binary search.

The number of old fixed points in a segment is obtained with a prefix sum. For a fixed sss, as lll increases, the number of newly created fixed points changes only after passing one of the stored values, while the number of old fixed points can only decrease. Therefore it is enough to test the smallest possible lll, and values of the form x+1x+1x+1 for stored values xxx.

Each position belongs to exactly one group s=i+Ais=i+A_is=i+Ai​, so the total number of tested candidates is O(N)O(N)O(N). The total time complexity is O(Nlog⁡N)O(N\log N) including sorting and binary searches, and the memory complexity is .

Solution written by GPT5.5

j​
=
j}+
#{j:
l≤
j≤
r, j+
Aj​=
l+
r}.
1
​
⌋
.
s−l][l,s-l]
[l,s−l]
l≤min⁡(j,Aj)l \leq \min(j,A_j)l≤min(j,Aj​)
sss
min⁡(j,Aj)\min(j,A_j)min(j,Aj​)
j+Aj=sj+A_j=sj+Aj​=s
lll
O
(
N
log
N
)
O(N)O(N)O(N)