353 传统题

[ABC485E] 异色路径 (Colorful Route)

时间限制
2000ms
内存限制
1024MiB
登顶 / 尝试
1/ 1
难度
4
    上传者 标签AtCoderABC 485普及+图论广度优先搜索最短路

[ABC485E] 异色路径 (Colorful Route)

Score : 450450 points

Problem Statement

There are NN cities and MM one-way roads. The ii-th road leads from city UiU_i to city ViV_i and is painted in color CiC_i.

You want to travel from city 11 to city NN by repeatedly traversing roads. However, you must not traverse roads painted in the same color twice in a row.

Determine whether it is possible to reach city NN from city 11, and if it is possible, find the minimum possible number of times you traverse a road.

Constraints

  • 2≤N≤2×1052 \leq N \leq 2 \times 10^5

  • 1≤M≤2×1051 \leq M \leq 2 \times 10^5

  • 1≤Ui,Vi≤N1 \leq U_i, V_i \leq N

  • Ui≠ViU_i \neq V_i

  • 1≤Ci≤M1 \leq C_i \leq M

  • All input values are integers.

Input

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

$N$ $M$
$U_1$ $V_1$ $C_1$
$U_2$ $V_2$ $C_2$
$\vdots$
$U_M$ $V_M$ $C_M$

Output

If it is impossible to reach city NN from city 11, print -1. Otherwise, print the minimum possible number of times you traverse a road.

Sample Input 1

6 10
1 2 1
2 4 2
2 5 2
3 6 5
4 3 3
5 2 3
5 3 2
5 6 2
6 1 3
6 5 3

Sample Output 1

4

Let road ii denote the ii-th road. You can reach city 66 by traversing roads 1,2,5,41, 2, 5, 4 in this order.

Sample Input 2

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

Sample Output 2

-1

Sample Input 3

8 10
1 2 1
2 3 2
2 4 1
3 2 3
4 5 2
4 6 1
5 4 3
6 7 2
6 8 1
7 6 3

Sample Output 3

10