Let's consider the following problem: For a directed acyclic graph G = (V,E)
we define the function "levels" for each vertex u, as l(u)
such that:
1. l(u)>=0 for every u
2. If there is a path from u to v (u -> v) then l(u)>l(v)
3. For each vertex u, l(u) is the minimum integer that satisfies both conditions 1 and 2.
The problem says:
a. Prove that for every DAG the above function is uniquely defined, i.e. it's the only function that satisfies conditions 1,2 and 3.
b. Find an O(|V| + |E|)
algorithm that calculates this function for every vertex.
Here is a possible algorithm based on topological sort:
First we find the transpose of G which is G^T
, defined as G^T = (V,E^T)
, where E^T={(u,v): (v,u) is in E}
which takes O(|V|+|E|)
in total if based on adjacency list implementation:
(O(|V|)
for allocation and sum for all v in V of |Adj[v]| = O(|E|))
. Topological sort takes Theta(|V|+|E|)
since it includes a BFS and |V|
insertions in list each of which take O(1)
.
TRANSPOSE(G){
Allocate |V| list pointers for G^T i.e. (Adj'[])
for(i = 1, i <= |V|, i++){
for every vertex v in Adj[i]{
add vertex i to Adj'[v]
}
}
}
L = TopSort(G)