#K57907. Longest Path in a Directed Acyclic Graph
Longest Path in a Directed Acyclic Graph
Longest Path in a Directed Acyclic Graph
You are given a directed acyclic graph (DAG) with n intersections (nodes) and m one-way roads (edges). Your task is to compute the length of the longest path in the graph. A path's length is measured by the number of edges in the path, and no intersection (node) is visited more than once.
Formally, let \(G = (V, E)\) be a DAG with \(|V| = n\) and \(|E| = m\). The goal is to find the maximum value of \(dp[v]\) over all nodes \(v\), where \(dp[v]\) represents the length of the longest path ending at node \(v\). The recurrence can be expressed as:
[ \text{dp}[v] = \max_{u\colon (u,v) \in E} {\text{dp}[u] + 1} ]
If a node has no incoming edges, then \(dp[v] = 0\). Output the maximum \(dp\) value among all nodes.
Note: The input guarantees that the graph is a DAG.
inputFormat
The first line contains two integers n
and m
, where n
is the number of intersections (nodes) and m
is the number of one-way roads (edges). Each of the next m
lines contains two integers u
and v
representing a road from node u
to node v
. It is guaranteed that the graph is a DAG.
Input is provided via standard input (stdin).
outputFormat
Output a single integer which is the length of the longest path (i.e., the maximum number of edges) in the DAG.
Output should be written to standard output (stdout).
## sample5 6
0 1
1 2
2 3
1 3
3 4
2 4
4