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

Back to problem

Editorial

Consider the cycle decomposition of PPP. Since Ai2=PA_i^2=PAi2​=P, we have AiP=PAiA_iP=PA_iAi​P=PAi​. Thus every AiA_iAi​ commutes with PPP, and maps each cycle of PPP only to another cycle of the same length. Hence the answer can be computed independently for each cycle length and multiplied.

Fix a length ddd, and let mmm be the number of cycles of length ddd in PPP. The action induced by the KKK permutations AiA_iA on these cycles can be viewed as an action of . Therefore, each connected component contains exactly cycles for some .

Let cd,rc_{d,r}cd,r​ be the number of ways to build one component on a fixed set of 2r2^r2r cycles.

If ddd is odd, then

cd,r=[Kr]2(2r−1)!d2r−1.c_{d,r} = {K \brack r}_2 (2^r-1)! d^{2^r-1}.cd,r​=[rK​

If ddd is even, then r=0r=0r=0 is impossible, and for r≥1r \ge 1r≥1,

cd,r=[K−1r−1]22K−r(2r−1)!d2r−1.c_{d,r} = {K-1 \brack r-1}_2 2^{K-r} (2^r-1)! d^{2^r-1}.cd,r​=[r

Here

[nr]2=∏i=0r−12n−i−12r−i−1{n \brack r}_2 = \prod_{i=0}^{r-1} \frac{2^{n-i}-1}{2^{r-i}-1}[rn​]2​=

is the Gaussian binomial coefficient over F2\mathbb F_2F2​. Since r≤log⁡2Nr \le \log_2 Nr≤log2​N, it can be computed efficiently even for very large KK.

Let F[n]F[n]F[n] be the number of ways to process nnn cycles of length ddd. If the component containing the first remaining cycle has size 2r2^r2r, we choose the other 2r−12^r-1 cycles from the remaining cycles. Thus

F[0]=1,F[0]=1,F[0]=1, F[n]=∑2r≤n(n−12r−1)cd,rF[n−2r].F[n] = \sum_{2^r \le n} \binom{n-1}{2^r-1} c_{d,r} F[n-2^r].F[n]=2r≤n∑​

Multiplying the values over all cycle lengths gives the answer. The total time complexity is O(Nlog⁡N)O(N\log N)O(NlogN).

i
​
F2K\mathbb F_2^KF2K​
2r2^r2r
rrr
]
2​
(
2r
−
1)!d2r−1.
−
1
K−1
​
]
2​
2K−r
(
2r
−
1)!d2r−1.
i=0∏r−1​
2r−i−12n−i−1​
K
2r
−
1
n−1n-1n−1
(2r−1n−1​)
cd,r​
F
[
n
−
2r].