Editorial
The cycle-related information can be handled using strongly connected components.
First, decompose the directed graph into strongly connected components. Any strongly connected component of size at least contains a cycle. Since the input contains no self-loops, a strongly connected component of size does not contain a cycle.
If each strongly connected component is contracted into one vertex, the resulting graph is a DAG. An original vertex can visit a cycle if and only if its strongly connected component can reach a strongly connected component that contains a cycle.
Therefore, we can solve the problem as follows.
- Find all strongly connected components of the graph.
- Mark every strongly connected component of size at least as a component containing a cycle.
- Build the reversed edges of the strongly connected component DAG.
- Starting from all components containing a cycle, run DFS or BFS along the reversed edges.
Every visited strongly connected component can reach a component containing a cycle in the original direction. Hence, the vertices belonging to unvisited components are exactly the vertices counted in the answer.
The time complexity is , and the memory complexity is .