This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: CMPT 307  Data Structures and Algorithms: Solutions to Problem Set 2 October 9, 2008 1. Topological ordering. Let G = ( V,E ) be a directed acyclic graph (DAG). A topo logical ordering of G is a sequence of its vertices v 1 ,v 2 ,...,v n so that for every edge ( v i ,v j ) E we have i < j (i.e., all edges point forward). It is a simple fact that every DAG has a topological ordering. Give an algorithm for finding a topological ordering for a given DAG G = ( V,E ) with the running time O (  V  +  E  ). (Hint: Do a careful implementation of the following algorithm: Find a vertex v without any incoming edges. Delete v from G . Recursively sort G , getting the ordered list L . Output v ; L ). Solution: Let us call a vertex live if it has not been deleted from the graph yet. The idea is to keep track of live vertices, and those live vertices that have no incoming edges from other live vertices. Let us call the live vertices with no incoming edges from other live vertices ready . For each live vertex, we will also keep track of the number of incoming edges from other live vertices. The algorithm will choose a ready vertex v , attach it to the end of the topological ordering found so far, and remove v from live . While removing v from live , the algorithm will look at all live vertices w with incoming edge from v , and subtract 1 from the count of incoming edges for each such w . If, during this process, we see a vertex w with edge count 0, we put such w into the set ready . Heres a more formal description of the algorithm: Algorithm TopoSort ( G = ( V,E )) % initally all vertices are live for each v V do live [ v ] True ; count [ v ] endfor % computing the number count of incoming edges for all vertices for each v V do for each edge ( v,w ) do count [ w ] count [ w ] + 1 endfor endfor Ready ; for each v V do if count [ v ] = 0 then Ready Ready { v } endif endfor 1 List hi ; while Ready 6 = do let v be (an arbitrary) vertex from Ready ; Ready Ready { v } ; List List,v ; live [ v ] False ; for each edge ( v,w ) do count [ w ] count [ w ] 1; if live [ w ]&( count [ w ] = 0) then Ready Ready { w } endif endfor endwhile return List Note that the initialization (the first three forloops) takes time O (  V  +  E  ). The whileloop runs at most  V  times, and so eventually terminates. To compute the running time for the whileloop, observe that each edge ( v,w ) is considered at most once, and so contributes a constant amount to the overall running time. Hence, the overall time of the whileloop is O (  E  ). The total time of the algorithm is O (  V  +  E  ), as required....
View
Full
Document
 Spring '09
 A.BULATOV
 Algorithms, Data Structures

Click to edit the document details