公式

C - Strongly Connected 解説 by evima


When the final graph is decomposed into strongly connected components, the set of vertex indices contained in each component forms an interval.
For \(i\,(1 \le i \le 2N-1)\), call \(i\) a cut if vertices \(i\) and \(i+1\) belong to different components. We need to count the ways to pair the vertices so that no cut exists.

For \(i\) to be a cut, there must be no edge that goes from a vertex whose index is at least \(i+1\) to a vertex whose index is at most \(i\). Equivalently, every black vertex with index at most \(i\) must be paired with some white vertex whose index is at most \(i\).

Let \(i_1<i_2<\dots<i_k\) be the cuts (all other \(i\) may or may not be cuts). For convenience, let \(i_0=0\) and \(i_{k+1}=2N\).

Process the black vertices in increasing order of their indices and decide which white vertex to pair with each. Consider the black vertices whose indices are between \(i_l+1\) and \(i_{l+1}\). Denote by \(B_i\) (resp. \(W_i\)) the number of black (resp. white) vertices with indices at most \(i\).

Because \(i_{l+1}\) is a cut, the number of candidate white vertices for pairing is the number of white vertices with indices at most \(i_{l+1}\) minus the number of white vertices already used for black vertices with indices at most \(i_l\), that is, \(W_{i_{l+1}}-B_{i_l}\). We must assign them to the \(B_{i_{l+1}}-B_{i_l}\) black vertices, so the number of such assignments is \(\dfrac{(W_{i_{l+1}}-B_{i_l})!}{(W_{i_{l+1}}-B_{i_{l+1}})!}\). However, if \(W_{i_{l+1}}<B_{i_{l+1}}\) or \(W_{i_{l+1}}<B_{i_l}\), this number is \(0\).

Applying the principle of inclusion–exclusion, we arrive at the recurrence whose value \(dp_{2N}\) is the answer:

  • \(dp_0 = -1\)

  • \(dp_i = \sum\limits_{j=0}^{i-1}(-1)dp_j\dfrac{(W_i-B_j)!}{(W_i-B_i)!}\)

Here, the contribution from \(dp_j\) to \(dp_i\) is \(0\) if \(W_i<B_i\) or \(W_i<B_j\).

We speed up this DP with divide‑and‑conquer and FFT.

For \(j=1,2,\dots,m\) and \(i=m+1,m+2,\dots,2m\), compute all contributions from \(j\) to \(i\) at once.

Define:

  • \(x_b=\sum\limits_{j\leq m, B_j=b}dp_j\)

  • \(y_s=s!\)

  • \(z_w=\sum\limits_{b+s=w}x_by_s\)

Then, the total contribution of \(j=1,2,\ldots,m\) to \(dp_i\) is \((-1)\dfrac{z_{W_i}}{(W_i-B_i)!}\). The range of \(b\) for which there is \(j\) with \(B_j=b\) has length at most \(m\), and the same goes for the range of \(w\) for which there is \(i\) with \(W_i=w\), so the time complexity of this convolution is \(O(m\log m)\).

Hence, the problem is solved in \(O(N\log^2N)\) time.

投稿日時:
最終更新: