Official

F - ABS Permutation (Count ver.) Editorial by evima


Let us solve the case \(M=1\).

Consider dividing \((1, 2, \dots, N)\) into some contiguous subsequences, reverse some of them with length \(2\) or more, and then permute them.

For example, we divide \((1,2,3,4,5,6)\) into \((1,2,3),(4),(5,6)\), reverse \((1,2,3)\) into \((3,2,1)\), and permute them into \((4,5,6,3,2,1)\).

When dividing the sequence, let us call the gap between \(i\) and \(i+1\) partition \(i\). Consider choosing some of the partitions \(1, 2, \dots, N-1\). We note that each time two consecutive partitions are chosen, the number of ways to perform reversion gets multiplied by \(\frac{1}{2}\). Now, we can find for every \(i\) the number of ways to get \(i\) subsequences and reverse them in \(O(N \log N)\) time with binary lifting, maintaining whether each of the partitions \(1\) and \(N\) are chosen when choosing \(K\) from consecutive \(N\) partitions.

Now, consider the case with general \(M\). Take a permutation \(Q\) such that \(Q_{P_i} =i \). Then, we have \(|P_i - P_{i+1}|=M \Leftrightarrow |Q_i-Q_{i+M}|=1\), so we can reduce it to the case \(M=1\) by classifying the indices in \(Q\) modulo \(K\). We merge these results in \(\mathrm{O}(N\log^2 N)\) time.

Let \(A_K\) be the answer for a fixed \(K\). What we have found is \(\sum_{j=0}^{N-1} \binom{j}{i} A_j\) for \(0 \le i \le N-1\), which we will denote by \(B_i\).

After appropriate replacements in \(B_i = \sum_{j=0}^{N-1} \binom{j}{i} A_j\), we get \(B_i = \sum_{j=0}^{N-1} \frac{A_j}{(j-i)!}\), from which we can determine \(A_j\) from top to bottom with divide-and-conquer FFT.

Now the problem has been solved in \(\mathrm{O}(N\log^2 N)\) time.

posted:
last update: