atcoder#ABC245F. [ABC245F] Endless Walk

[ABC245F] Endless Walk

Score : 500500 points

Problem Statement

We have a simple directed graph GG with NN vertices and MM edges. The vertices are labeled as Vertex 11, Vertex 22, \ldots, Vertex NN. The ii-th edge (1iM)(1\leq i\leq M) goes from Vertex UiU_i to Vertex ViV_i.

Takahashi will start at a vertex and repeatedly travel on GG from one vertex to another along a directed edge. How many vertices of GG have the following condition: Takahashi can start at that vertex and continue traveling indefinitely by carefully choosing the path?

Constraints

  • 1N2×1051 \leq N \leq 2\times 10^5
  • 0Mmin(N(N1),2×105)0 \leq M \leq \min(N(N-1), 2\times 10^5)
  • 1Ui,ViN1 \leq U_i,V_i\leq N
  • UiViU_i\neq V_i
  • (Ui,Vi)(Uj,Vj)(U_i,V_i)\neq (U_j,V_j) if iji\neq j.
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN MM

U1U_1 V1V_1

U2U_2 V2V_2

\vdots

UMU_M VMV_M

Output

Print the answer.

5 5
1 2
2 3
3 4
4 2
4 5
4

When starting at Vertex 22, Takahashi can continue traveling indefinitely: 22 \to 33 \to 44 \to 22 \to 33 \to \cdots The same goes when starting at Vertex 33 or Vertex 44. From Vertex 11, he can first go to Vertex 22 and then continue traveling indefinitely again. On the other hand, from Vertex 55, he cannot move at all.

Thus, four vertices ―Vertex 11, 22, 33, and 44― satisfy the conditions, so 44 should be printed.

3 2
1 2
2 1
2

Note that, in a simple directed graph, there may be two edges in opposite directions between the same pair of vertices. Additionally, GG may not be connected.