[ABC485E] 异色路径 (Colorful Route)
Score : points
Problem Statement
There are cities and one-way roads. The -th road leads from city to city and is painted in color .
You want to travel from city to city 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 from city , and if it is possible, find the minimum possible number of times you traverse a road.
Constraints
-
-
-
-
-
-
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 from city , 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 denote the -th road. You can reach city by traversing roads 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