Minimum Cost Path in DAGHard

Minimum Cost Path in DAG

Hard+150 XP · +50 Aurasortinggraphsdijkstra

You are given a Directed Acyclic Graph (DAG) with N vertices and M directed edges. Each edge has a weight of either 0 or 1. Find the minimum cost path from vertex 0 to vertex N-1. If vertex N-1 is unreachable from vertex 0, output -1.

Input

The first line contains two integers N and M (2 <= N <= 200000, 1 <= M <= 200000). The next M lines describe the edges. Each line contains three integers u, v, and w, where u and v are the source and destination vertices (0-indexed), and w is the edge weight (0 or 1).

Output

Print a single integer: the minimum cost to reach vertex N-1 from vertex 0. If N-1 is unreachable, print -1.

Constraints

2 <= N <= 200000 1 <= M <= 200000 0 <= u, v < N u != v 0 <= w <= 1

Time limit 2 s (native code; slower languages get more)Memory 256 MB17 hidden tests

Example 1

Input
5 6
0 1 0
0 2 1
1 3 1
2 3 0
3 4 0
1 4 1
Output
1

Path 0->2->3->4 has cost 0+0+0=0. Path 0->1->3->4 has cost 0+1+0=1. Path 0->1->4 has cost 0+1=1.

Example 2

Input
3 2
0 1 1
1 2 1
Output
2

The only path is 0->1->2 with cost 1+1=2.

Hints