E - Reachability in Functional Graph Editorial by en_translator
The graph given in this problem is called a functional graph. Functional graph is a popular theme in competitive programming, so grasp the properties of the graph.
A notable property of a functional feature is as follows:
*A property of a functional graph
If \(G\) has \(K\) connected components \(C_1, C_2, \dots, C_K\), each of them has exactly one cycle.
The proof is presented in the editorial of ABC256 E.
Let us use this property to solve this problem. We consider each connected component independently. A connected component has a cycle with directed trees attached, as shown below.
For example, we enumerate vertices reachable from some of the vertices in the figure.
- From vertex \(1\), one can reachable vertices \(1, 2, 3\).
- From vertex \(4\), one can reachable vertices \(1, 2, 3, 4\).
- From vertex \(7\), one can reachable vertices \(1,2,3,5,7\).
Generalizing this feature, we find the following fact. (Proof omitted.)
The vertices reachable from vertex \(u\) are exhaustively classified into the following two types:
- an ancestor of \(u\) in the directed tree containing vertex \(u\)
- a vertex contained in the cycle containing the root of the directed tree containing vertex \(u\)
With this property, all that left is to compute
- the depth of \(u\) in the directed tree containing vertex \(u\), and
- the number of vertices in the cycle containing the root of the directed tree containing vertex \(u\),
using a graph search algorithm like DFS (Depth-First Search). The complexity is \(\mathrm{O}(N)\), which is fast enough.
Alternatively, one can use the strongly connected component (SCC) algorithm. Consider it if you are interested.
posted:
last update: