#abc245f. F - Endless Walk

F - Endless Walk

Score : 500500 points

问题描述

我们有一个简单的有向图 GG,包含 NN 个顶点和 MM 条边。顶点被标记为顶点 11、顶点 22\ldots、顶点 NN。第 ii 条边(1iM1\leq i\leq M)从顶点 UiU_i 指向顶点 ViV_i

Takahashi 将从一个顶点开始,并沿一条有向边在图 GG 上重复地从一个顶点移动到另一个顶点。请问图 GG 中有多少个顶点满足以下条件:Takahashi 可以从该顶点开始,并通过精心选择路径无限次地继续旅行?

以上为通义千问 qwen-max 翻译,仅供参考。

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.

Sample Input 1

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

Sample Output 1

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.

Sample Input 2

3 2
1 2
2 1

Sample Output 2

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.

update @ 2024/3/10 10:32:07