A - Row and Col swap Editorial by evima Editorial for printing
For each \(i\), fix which of the following eventually belongs to \(P\): the element \(i\) of \(P\), or that of \(Q\). Then the problem becomes: “On a \(2 \times N\) board, \(0\) and \(1\) are each written \(N\) times. We perform an operation \(M\) times where we swap the integers written in two cells that share a row or column. How many sequences of operations result in the top row having \(N\) \(0\)s and the bottom row having \(N\) \(1\)s?”
The board is characterized by the numbers \(a,b,c,d\) of indices \(i\) such that \((X_{1,i},X_{2,i}) = (0,0),(0,1),(1,0),(1,1)\), respectively. Since \(a+b+c+d=N\) and \(a=d\) hold, once \(a\) and \(b\) are determined, \(c\) and \(d\) are also determined. Thus, we can run a DP where \(dp[k][x][y] =\) the number of operation sequences of length \(k\) resulting in \(a=x\) and \(b=y\).
To find the initial state, we need to compute the distribution of \((a,b)\) over the \(2^N\) ways of rewriting one of \(P_i\) and \(Q_i\) as \(0\) and the other as \(1\). This can be found by, in the set of cycles formed by drawing an edge from \(P_i\) to \(Q_i\), running a DP for each cycle. Specifically, if there is a cycle \(1 \rightarrow 2 \rightarrow \dots \rightarrow k \rightarrow 1\), we can run this DP: \(dp[i][x][y][z] =\) the number of ways, having decided the assignment of \(0\) and \(1\) up to \(i\), such that currently \(a=x,b=y\), and element \(1\) of \(Q\) has been rewritten to \(z\).
To combine the results across cycles, you can either keep using the same DP array, which takes \(\mathrm{O}(N^3)\) time, or run the DP independently for each cycle and combine them via convolution in \(\mathrm{O}(N^2 \log^2 N)\). In the latter case, it is convenient to associate the number of ways of achieving \((a,b)\) with the coefficient of \(x^{a + (N+1)b}\).
Thus, this problem can be solved in \(\mathrm{O}(N^3 + N^2M)\) overall.
posted:
last update: