Minimum Cost Path in DAG
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
Example 1
5 6 0 1 0 0 2 1 1 3 1 2 3 0 3 4 0 1 4 1
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
3 2 0 1 1 1 2 1
2
The only path is 0->1->2 with cost 1+1=2.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
5 6 0 1 0 0 2 1 1 3 1 2 3 0 3 4 0 1 4 1
3 2 0 1 1 1 2 1