#abc376d. D - Cycle

D - Cycle

Score : 400400 points

问题陈述

有一个简单的有向图,包含NN个顶点,编号从11NN,以及MM条边。第ii条边(1iM1 \leq i \leq M)是从顶点aia_i指向顶点bib_i的有向边。 判断是否存在包含顶点11的环,如果存在,找出这样的环中边数最少的环。

以上为大语言模型 kimi 翻译,仅供参考。

Problem Statement

There is a simple directed graph with NN vertices numbered from 11 to NN and MM edges. The ii-th edge (1iM)(1 \leq i \leq M) is a directed edge from vertex aia_i to vertex bib_i.
Determine whether there exists a cycle that contains vertex 11, and if it exists, find the minimum number of edges among such cycles.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • $1 \leq M \leq \min \left( \frac{N(N-1)}{2},\ 2 \times 10^5 \right)$
  • 1aiN1 \leq a_i \leq N
  • 1biN1 \leq b_i \leq N
  • aibia_i \neq b_i
  • (ai,bi)(aj,bj)(a_i, b_i) \neq (a_j, b_j) and (ai,bi)(bj,aj)(a_i, b_i) \neq (b_j, a_j), if iji \neq j.
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

NN MM

a1a_1 b1b_1

a2a_2 b2b_2

\vdots

aMa_M bMb_M

Output

If there exists a cycle that contains vertex 11, print the minimum number of edges among such cycles. Otherwise, print -1.

Sample Input 1

3 3
1 2
2 3
3 1

Sample Output 1

3

Vertex 11 \to vertex 22 \to vertex 33 \to vertex 11 is a cycle with three edges, and this is the only cycle that contains vertex 11.

Sample Input 2

3 2
1 2
2 3

Sample Output 2

-1

Sample Input 3

6 9
6 1
1 5
2 6
2 1
3 6
4 2
6 4
3 5
5 4

Sample Output 3

4