Sie sind auf Seite 1von 2

46

L ECTURE 23
Topological sort of a DAG: an example Deleting a vertex i can be achieved by simply decrementing the indegrees of all the vertices j such that (i, j) is an edge in the graph Pseudo-code: Compute indegrees for all the vertices in G for (int k = 0; k < |V|; k++){ let i denote a vertex with (indegree[i] == 0); if no such node then return failure; for each edge (i,j) do indegree[j] -= 1; } Analysis for adjacency matrix: 2 O(|V | ) to compute the indegrees; During each iteration, O(|V |) for nd the node i, plus O(|V |) to update the indegrees 2 2 2 So total run-time is O(|V | ) + O(|V | ), or O(|V | ). Analysis for adjacency list: O(|V | + |E|) to compute the indegrees; 2 During each iteration, O(|V |) for nd the node i: therefore, O(|V | ) over all iterations no better than adjacency matrix representation!! An improvement to the algorithm: ag a node when its indegree becomes zero, so that a zero-indegree vertex can be detected in constant time inside the loop. Compute indegrees for all the vertices in G Place zero-indegree vertices in a queue Q for (int k = 0; k < |V|; k++){ i = Q.front(); if Q is empty return failure Q.dequeue(); for each edge (i,j) do{ indegree[j] -= 1; if (indegree[j] == 0) Q.enqueue(j); } } Analysis for adjacency list: O(|V | + |E|) to compute the indegrees; O(|V |) to place zero-indegree vertices in A During each iteration, O(1) to nd the node i Over all iterations of the loop, O(|E|) to update the indegrees So total run-time is O(|V | + |E|) + O(|V |) + O(|V |) + O(|E|), or O(|V| + |E|). (Which is the best we can hope for: look at each vertex and each edge.) Questions: 1) What if we had used a stack instead of a queue?? 2) What if we had gone backwards (look for nodes with (outdegree == 0)) instead?

47

Shortest path problems


Cost of the path v1 , v2 , . . . , vN :

The problem of negative edge-costs negative cycles versus negative edges. Different kinds of shortest-path (SP) problems: Single-source single-destination: Given weighted graph G = (V, E) and vertices s, t V , nd the shortest path from s to t Single-source (all-destinations): Given weighted graph G = (V, E) and a vertex s V , nd the shortest path from s to all other vertices in the graph All pairs: Given weighted graph G = (V, E), nd the shortest path between each pair of vertices

N 1 i=1

c(vi , vi+1 )

Single source problems Turns out that in the worst case, algorithm for single-source single destination is equivalent to single-source all destinations. So we only consider single-source all destinations. First, a special case: all c(vi , vj ) = 1 (equivalently, unweighted graph) Algorithm is Breadth-First Search (BFS) Example: page 368 (Fig 9.10) The data elds we will maintain: for each vertex v{ d[v] = infinity; // length of shortest path known thus far p[v] = s; // last vertex on this shortest path known[v] = false; // set to true when we KNOW shortest path has been discovered... }

Das könnte Ihnen auch gefallen