Docsity

Introduction to Algorithms, Lecture Notes - Computer Science - 4, Study notes of Introduction to Computers

Toggle sidebar
bg1
Chapter 3
Decompositions of graphs
3.1 Why graphs?
A wide range of problems can be expressed with clarity and precision in the concise pictorial
language of graphs. For instance, consider the task of coloring a political map. What is the
minimum number of colors needed, with the obvious restriction that neighboring countries
should have different colors? One of the difficulties in attacking this problem is that the map
itself, even a stripped-down version like Figure 3.1(a), is usually cluttered with irrelevant
information: intricate boundaries, border posts where three or more countries meet, open
seas, and meandering rivers. Such distractions are absent from the mathematical object of
Figure 3.1(b), a graph with one vertex for each country (1 is Brazil, 11 is Argentina) and edges
between neighbors. It contains exactly the information needed for coloring, and nothing more.
The precise goal is now to assign a color to each vertex so that no edge has endpoints of the
same color.
Graph coloring is not the exclusive domain of map designers. Suppose a university needs
to schedule examinations for all its classes and wants to use the fewest time slots possible.
The only constraint is that two exams cannot be scheduled concurrently if some student will
be taking both of them. To express this problem as a graph, use one vertex for each exam and
put an edge between two vertices if there is a conflict, that is, if there is somebody taking both
endpoint exams. Think of each time slot as having its own color. Then, assigning time slots is
exactly the same as coloring this graph!
Some basic operations on graphs arise with such frequency, and in such a diversity of con-
texts, that a lot of effort has gone into finding efficient procedures for them. This chapter is
devoted to some of the most fundamental of these algorithms—those that uncover the basic
connectivity structure of a graph.
Formally, a graph is specified by a set of vertices (also called nodes)Vand by edges E
between select pairs of vertices. In the map example, V={1,2,3,...,13}and Eincludes,
among many other edges, {1,2},{9,11}, and {7,13}. Here an edge between xand yspecifically
means “xshares a border with y.” This is a symmetric relation—it implies also that yshares
a border with x—and we denote it using set notation, e={x, y}. Such edges are undirected
91
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

Partial preview of the text

Download Introduction to Algorithms, Lecture Notes - Computer Science - 4 and more Study notes Introduction to Computers in PDF only on Docsity!

Chapter 3

Decompositions of graphs

3.1 Why graphs?

A wide range of problems can be expressed with clarity and precision in the concise pictorial language of graphs. For instance, consider the task of coloring a political map. What is the minimum number of colors needed, with the obvious restriction that neighboring countries should have different colors? One of the difficulties in attacking this problem is that the map itself, even a stripped-down version like Figure 3.1(a), is usually cluttered with irrelevant information: intricate boundaries, border posts where three or more countries meet, open seas, and meandering rivers. Such distractions are absent from the mathematical object of Figure 3.1(b), a graph with one vertex for each country (1 is Brazil, 11 is Argentina) and edges between neighbors. It contains exactly the information needed for coloring, and nothing more. The precise goal is now to assign a color to each vertex so that no edge has endpoints of the same color. Graph coloring is not the exclusive domain of map designers. Suppose a university needs to schedule examinations for all its classes and wants to use the fewest time slots possible. The only constraint is that two exams cannot be scheduled concurrently if some student will be taking both of them. To express this problem as a graph, use one vertex for each exam and put an edge between two vertices if there is a conflict, that is, if there is somebody taking both endpoint exams. Think of each time slot as having its own color. Then, assigning time slots is exactly the same as coloring this graph! Some basic operations on graphs arise with such frequency, and in such a diversity of con- texts, that a lot of effort has gone into finding efficient procedures for them. This chapter is devoted to some of the most fundamental of these algorithms—those that uncover the basic connectivity structure of a graph.

Formally, a graph is specified by a set of vertices (also called nodes ) V and by edges E between select pairs of vertices. In the map example, V = { 1 , 2 , 3 ,... , 13 } and E includes, among many other edges, { 1 , 2 }, { 9 , 11 }, and { 7 , 13 }. Here an edge between x and y specifically means “x shares a border with y.” This is a symmetric relation—it implies also that y shares a border with x—and we denote it using set notation, e = {x, y}. Such edges are undirected

91

92 Algorithms

Figure 3.1 (a) A map and (b) its graph.

(a) (b)

and are part of an undirected graph. Sometimes graphs depict relations that do not have this reciprocity, in which case it is necessary to use edges with directions on them. There can be directed edges e from x to y (written e = (x, y)), or from y to x (written (y, x)), or both. A particularly enormous example of a directed graph is the graph of all links in the World Wide Web. It has a vertex for each site on the Internet, and a directed edge (u, v) whenever site u has a link to site v: in total, billions of nodes and edges! Understanding even the most basic connectivity properties of the Web is of great economic and social interest. Although the size of this problem is daunting, we will soon see that a lot of valuable information about the structure of a graph can, happily, be determined in just linear time.

3.1.1 How is a graph represented?

We can represent a graph by an adjacency matrix ; if there are n = |V | vertices v 1 ,... , vn, this is an n × n array whose (i, j)th entry is

aij =

1 if there is an edge from vi to vj 0 otherwise.

For undirected graphs, the matrix is symmetric since an edge {u, v} can be taken in either direction. The biggest convenience of this format is that the presence of a particular edge can be checked in constant time, with just one memory access. On the other hand the matrix takes

94 Algorithms

Figure 3.2 Exploring a graph is rather like navigating a maze.

A

C

B

F

D

H (^) I J

K

E

G

L

H

G

A D

C

F

K

L

J

I

B

E

What parts of the graph are reachable from a given vertex?

To understand this task, try putting yourself in the position of a computer that has just been given a new graph, say in the form of an adjacency list. This representation offers just one basic operation: finding the neighbors of a vertex. With only this primitive, the reachability problem is rather like exploring a labyrinth (Figure 3.2). You start walking from a fixed place and whenever you arrive at any junction (vertex) there are a variety of passages (edges) you can follow. A careless choice of passages might lead you around in circles or might cause you to overlook some accessible part of the maze. Clearly, you need to record some intermediate information during exploration. This classic challenge has amused people for centuries. Everybody knows that all you need to explore a labyrinth is a ball of string and a piece of chalk. The chalk prevents looping, by marking the junctions you have already visited. The string always takes you back to the starting place, enabling you to return to passages that you previously saw but did not yet investigate. How can we simulate these two primitives, chalk and string, on a computer? The chalk marks are easy: for each vertex, maintain a Boolean variable indicating whether it has been visited already. As for the ball of string, the correct cyberanalog is a stack. After all, the exact role of the string is to offer two primitive operations— unwind to get to a new junction (the stack equivalent is to push the new vertex) and rewind to return to the previous junction ( pop the stack). Instead of explicitly maintaining a stack, we will do so implicitly via recursion (which is implemented using a stack of activation records). The resulting algorithm is shown in Figure 3.3.^1 The previsit and postvisit procedures are optional, meant for performing operations on a vertex when it is first discovered and also when it is being left for the last time. We will soon see some creative uses for them. (^1) As with many of our graph algorithms, this one applies to both undirected and directed graphs. In such cases, we adopt the directed notation for edges, (x, y). If the graph is undirected, then each of its edges should be thought of as existing in both directions: (x, y) and (y, x).

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 95

Figure 3.3 Finding all nodes reachable from a particular node.

procedure explore(G, v) Input: G = (V, E) is a graph; v ∈ V Output: visited(u) is set to true for all nodes u reachable from v

visited(v) = true previsit(v) for each edge (v, u) ∈ E: if not visited(u): explore(u) postvisit(v)

More immediately, we need to confirm that explore always works correctly. It certainly does not venture too far, because it only moves from nodes to their neighbors and can therefore never jump to a region that is not reachable from v. But does it find all vertices reachable from v? Well, if there is some u that it misses, choose any path from v to u, and look at the last vertex on that path that the procedure actually visited. Call this node z, and let w be the node immediately after it on the same path.

v z w u

So z was visited but w was not. This is a contradiction: while the explore procedure was at node z, it would have noticed w and moved on to it.

Incidentally, this pattern of reasoning arises often in the study of graphs and is in essence a streamlined induction. A more formal inductive proof would start by framing a hypothesis, such as “for any k ≥ 0 , all nodes within k hops from v get visited.” The base case is as usual trivial, since v is certainly visited. And the general case—showing that if all nodes k hops away are visited, then so are all nodes k + 1 hops away—is precisely the same point we just argued.

Figure 3.4 shows the result of running explore on our earlier example graph, starting at node A, and breaking ties in alphabetical order whenever there is a choice of nodes to visit. The solid edges are those that were actually traversed, each of which was elicited by a call to explore and led to the discovery of a new vertex. For instance, while B was being visited, the edge B − E was noticed and, since E was as yet unknown, was traversed via a call to explore(E). These solid edges form a tree (a connected graph with no cycles) and are therefore called tree edges. The dotted edges were ignored because they led back to familiar terrain, to vertices previously visited. They are called back edges.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 97

Figure 3.6 (a) A 12-node graph. (b) DFS search forest.

(a) A B (^) C D

E F^ G H

I J K L

(b) (^) A

B E

I

J G

K

C^ F

D

H

L

1,

2,

4,

5,

6,

11,22 23,

12,

13,

14,

15,

18,

has a running time of O(|V | + |E|), linear in the size of its input. This is as efficient as we could possibly hope for, since it takes this long even just to read the adjacency list. Figure 3.6 shows the outcome of depth-first search on a 12-node graph, once again break- ing ties alphabetically (ignore the pairs of numbers for the time being). The outer loop of DFS calls explore three times, on A, C, and finally F. As a result, there are three trees, each rooted at one of these starting points. Together they constitute a forest.

3.2.3 Connectivity in undirected graphs

An undirected graph is connected if there is a path between any pair of vertices. The graph of Figure 3.6 is not connected because, for instance, there is no path from A to K. However, it does have three disjoint connected regions, corresponding to the following sets of vertices:

{A, B, E, I, J} {C, D, G, H, K, L} {F }

These regions are called connected components : each of them is a subgraph that is internally connected but has no edges to the remaining vertices. When explore is started at a particular vertex, it identifies precisely the connected component containing that vertex. And each time the DFS outer loop calls explore, a new connected component is picked out. Thus depth-first search is trivially adapted to check if a graph is connected and, more generally, to assign each node v an integer ccnum[v] identifying the connected component to which it belongs. All it takes is

procedure previsit(v) ccnum[v] = cc

where cc needs to be initialized to zero and to be incremented each time the DFS procedure calls explore.

98 Algorithms

3.2.4 Previsit and postvisit orderings

We have seen how depth-first search—a few unassuming lines of code—is able to uncover the connectivity structure of an undirected graph in just linear time. But it is far more versatile than this. In order to stretch it further, we will collect a little more information during the ex- ploration process: for each node, we will note down the times of two important events, the mo- ment of first discovery (corresponding to previsit) and that of final departure (postvisit). Figure 3.6 shows these numbers for our earlier example, in which there are 24 events. The fifth event is the discovery of I. The 21 st event consists of leaving D behind for good.

One way to generate arrays pre and post with these numbers is to define a simple counter clock, initially set to 1, which gets updated as follows.

procedure previsit(v) pre[v] = clock clock = clock + 1

procedure postvisit(v) post[v] = clock clock = clock + 1

These timings will soon take on larger significance. Meanwhile, you might have noticed from Figure 3.4 that:

Property For any nodes u and v , the two intervals [ pre(u), post(u)] and [ pre(v), post(v)] are either disjoint or one is contained within the other.

Why? Because [pre(u), post(u)] is essentially the time during which vertex u was on the stack. The last-in, first-out behavior of a stack explains the rest.

3.3 Depth-first search in directed graphs

3.3.1 Types of edges

Our depth-first search algorithm can be run verbatim on directed graphs, taking care to tra- verse edges only in their prescribed directions. Figure 3.7 shows an example and the search tree that results when vertices are considered in lexicographic order. In further analyzing the directed case, it helps to have terminology for important relation- ships between nodes of a tree. A is the root of the search tree; everything else is its descendant. Similarly, E has descendants F , G, and H, and conversely, is an ancestor of these three nodes. The family analogy is carried further: C is the parent of D, which is its child. For undirected graphs we distinguished between tree edges and nontree edges. In the directed case, there is a slightly more elaborate taxonomy:

100 Algorithms

it follows that they, too, can be read off from pre and post numbers. Here is a summary of the various possibilities for an edge (u, v):

pre / post ordering for (u, v) Edge type

u v v u

Tree/forward

v u u v

Back

v v u u

Cross

You can confirm each of these characterizations by consulting the diagram of edge types. Do you see why no other orderings are possible?

3.3.2 Directed acyclic graphs

A cycle in a directed graph is a circular path v 0 → v 1 → v 2 → · · · → vk → v 0. Figure 3.7 has quite a few of them, for example, B → E → F → B. A graph without cycles is acyclic. It turns out we can test for acyclicity in linear time, with a single depth-first search.

Property A directed graph has a cycle if and only if its depth-first search reveals a back edge.

Proof. One direction is quite easy: if (u, v) is a back edge, then there is a cycle consisting of this edge together with the path from v to u in the search tree. Conversely, if the graph has a cycle v 0 → v 1 → · · · → vk → v 0 , look at the first node on this cycle to be discovered (the node with the lowest pre number). Suppose it is vi. All the other vj on the cycle are reachable from it and will therefore be its descendants in the search tree. In particular, the edge vi− 1 → vi (or vk → v 0 if i = 0) leads from a node to its ancestor and is thus by definition a back edge.

Directed acyclic graphs , or dags for short, come up all the time. They are good for modeling relations like causalities, hierarchies, and temporal dependencies. For example, suppose that you need to perform many tasks, but some of them cannot begin until certain others are completed (you have to wake up before you can get out of bed; you have to be out of bed, but not yet dressed, to take a shower; and so on). The question then is, what is a valid order in which to perform the tasks? Such constraints are conveniently represented by a directed graph in which each task is a node, and there is an edge from u to v if u is a precondition for v. In other words, before performing a task, all the tasks pointing to it must be completed. If this graph has a cycle, there is no hope: no ordering can possibly work. If on the other hand the graph is a dag, we would like if possible to linearize (or topologically sort ) it, to order the vertices one after the other in such a way that each edge goes from an earlier vertex to a later vertex, so that all precedence constraints are satisfied. In Figure 3.8, for instance, one valid ordering is B, A, D, C, E, F. (Can you spot the other three?)

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 101

Figure 3.8 A directed acyclic graph with one source, two sinks, and four possible lineariza- tions.

A

B

C

D

E

F

What types of dags can be linearized? Simple: All of them. And once again depth-first search tells us exactly how to do it: simply perform tasks in decreasing order of their post numbers. After all, the only edges (u, v) in a graph for which post(u) <post(v) are back edges (recall the table of edge types on page 100)—and we have seen that a dag cannot have back edges. Therefore:

Property In a dag, every edge leads to a vertex with a lower post number.

This gives us a linear-time algorithm for ordering the nodes of a dag. And, together with our earlier observations, it tells us that three rather different-sounding properties—acyclicity, linearizability, and the absence of back edges during a depth-first search—are in fact one and the same thing.

Since a dag is linearized by decreasing post numbers, the vertex with the smallest post number comes last in this linearization, and it must be a sink —no outgoing edges. Symmet- rically, the one with the highest post is a source , a node with no incoming edges.

Property Every dag has at least one source and at least one sink.

The guaranteed existence of a source suggests an alternative approach to linearization:

Find a source, output it, and delete it from the graph. Repeat until the graph is empty.

Can you see why this generates a valid linearization for any dag? What happens if the graph has cycles? And, how can this algorithm be implemented in linear time? (Exercise 3.14.)

3.4 Strongly connected components

3.4.1 Defining connectivity for directed graphs

Connectivity in undirected graphs is pretty straightforward: a graph that is not connected can be decomposed in a natural and obvious manner into several connected components (Fig-

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 103

can be linearized. If we want finer detail, we can look inside one of the nodes of this dag and examine the full-fledged strongly connected component within.

3.4.2 An efficient algorithm

The decomposition of a directed graph into its strongly connected components is very infor- mative and useful. It turns out, fortunately, that it can be found in linear time by making further use of depth-first search. The algorithm is based on some properties we have already seen but which we will now pinpoint more closely.

Property 1 If the explore subroutine is started at node u , then it will terminate precisely when all nodes reachable from u have been visited.

Therefore, if we call explore on a node that lies somewhere in a sink strongly connected component (a strongly connected component that is a sink in the meta-graph), then we will retrieve exactly that component. Figure 3.9 has two sink strongly connected components. Starting explore at node K, for instance, will completely traverse the larger of them and then stop. This suggests a way of finding one strongly connected component, but still leaves open two major problems: (A) how do we find a node that we know for sure lies in a sink strongly con- nected component and (B) how do we continue once this first component has been discovered? Let’s start with problem (A). There is not an easy, direct way to pick out a node that is guaranteed to lie in a sink strongly connected component. But there is a way to get a node in a source strongly connected component.

Property 2 The node that receives the highest post number in a depth-first search must lie in a source strongly connected component.

This follows from the following more general property.

Property 3 If C and C′ are strongly connected components, and there is an edge from a node in C to a node in C′ , then the highest post number in C is bigger than the highest post number in C′.

Proof. In proving Property 3, there are two cases to consider. If the depth-first search visits component C before component C ′, then clearly all of C and C′^ will be traversed before the procedure gets stuck (see Property 1). Therefore the first node visited in C will have a higher post number than any node of C′. On the other hand, if C′^ gets visited first, then the depth- first search will get stuck after seeing all of C ′^ but before seeing any of C, in which case the property follows immediately.

Property 3 can be restated as saying that the strongly connected components can be lin- earized by arranging them in decreasing order of their highest post numbers. This is a gen- eralization of our earlier algorithm for linearizing dags; in a dag, each node is a singleton strongly connected component. Property 2 helps us find a node in the source strongly connected component of G. How- ever, what we need is a node in the sink component. Our means seem to be the opposite of

104 Algorithms

Figure 3.10 The reverse of the graph from Figure 3.9.

A

D E

C

F

B

G H

K

L

I J

A B,E C,F

D G,H,IJ,K,L

our needs! But consider the reverse graph GR, the same as G but with all edges reversed (Figure 3.10). GR^ has exactly the same strongly connected components as G (why?). So, if we do a depth-first search of GR, the node with the highest post number will come from a source strongly connected component in GR, which is to say a sink strongly connected component in G. We have solved problem (A)! Onward to problem (B). How do we continue after the first sink component is identified? The solution is also provided by Property 3. Once we have found the first strongly connected component and deleted it from the graph, the node with the highest post number among those remaining will belong to a sink strongly connected component of whatever remains of G. Therefore we can keep using the post numbering from our initial depth-first search on GR to successively output the second strongly connected component, the third strongly connected component, and so on. The resulting algorithm is this.

  1. Run depth-first search on GR.
  2. Run the undirected connected components algorithm (from Section 3.2.3) on G, and dur- ing the depth-first search, process the vertices in decreasing order of their post numbers from step 1.

This algorithm is linear-time, only the constant in the linear term is about twice that of straight depth-first search. (Question: How does one construct an adjacency list represen- tation of GR^ in linear time? And how, in linear time, does one order the vertices of G by decreasing post values?)

106 Algorithms

Exercises

3.1. Perform a depth-first search on the following graph; whenever there’s a choice of vertices, pick the one that is alphabetically first. Classify each edge as a tree edge or back edge, and give the pre and post number of each vertex.

A B C

D E F

G H^ I

3.2. Perform depth-first search on each of the following graphs; whenever there’s a choice of vertices, pick the one that is alphabetically first. Classify each edge as a tree edge, forward edge, back edge, or cross edge, and give the pre and post number of each vertex.

(a)

F

A (^) B C

E D

G H

(b)

F

C

A B

H

G

E

D

3.3. Run the DFS-based topological ordering algorithm on the following graph. Whenever you have a choice of vertices to explore, always pick the one that is alphabetically first.

A

C E

D F

B

G

H

(a) Indicate the pre and post numbers of the nodes. (b) What are the sources and sinks of the graph? (c) What topological ordering is found by the algorithm? (d) How many topological orderings does this graph have? 3.4. Run the strongly connected components algorithm on the following directed graphs G. When doing DFS on GR: whenever there is a choice of vertices to explore, always pick the one that is alphabetically first.

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 107

(i) A

B E

G H

I

C D

F

J

(ii)

A (^) B C

D E^ F

G H I

In each case answer the following questions.

(a) In what order are the strongly connected components (SCCs) found? (b) Which are source SCCs and which are sink SCCs? (c) Draw the “metagraph” (each meta-node is an SCC of G). (d) What is the minimum number of edges you must add to this graph to make it strongly connected?

3.5. The reverse of a directed graph G = (V, E) is another directed graph GR^ = (V, ER) on the same vertex set, but with all edges reversed; that is, ER^ = {(v, u) : (u, v) ∈ E}. Give a linear-time algorithm for computing the reverse of a graph in adjacency list format. 3.6. In an undirected graph, the degree d(u) of a vertex u is the number of neighbors u has, or equiv- alently, the number of edges incident upon it. In a directed graph, we distinguish between the indegree din(u), which is the number of edges into u, and the outdegree dout(u), the number of edges leaving u.

(a) Show that in an undirected graph,

∑ u∈V d(u) = 2|E|. (b) Use part (a) to show that in an undirected graph, there must be an even number of vertices whose degree is odd. (c) Does a similar statement hold for the number of vertices with odd indegree in a directed graph?

3.7. A bipartite graph is a graph G = (V, E) whose vertices can be partitioned into two sets (V = V 1 ∪V 2 and V 1 ∩ V 2 = ∅) such that there are no edges between vertices in the same set (for instance, if u, v ∈ V 1 , then there is no edge between u and v).

(a) Give a linear-time algorithm to determine whether an undirected graph is bipartite. (b) There are many other ways to formulate this property. For instance, an undirected graph is bipartite if and only if it can be colored with just two colors. Prove the following formulation: an undirected graph is bipartite if and only if it contains no cycles of odd length. (c) At most how many colors are needed to color in an undirected graph with exactly one odd- length cycle?

S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani 109

(b) Suppose it now turns out that the mayor’s original claim is false. She next claims something weaker: if you start driving from town hall, navigating one-way streets, then no matter where you reach, there is always a way to drive legally back to the town hall. Formulate this weaker property as a graph-theoretic problem, and carefully show how it too can be checked in linear time.

3.16. Suppose a CS curriculum consists of n courses, all of them mandatory. The prerequisite graph G has a node for each course, and an edge from course v to course w if and only if v is a prerequisite for w. Find an algorithm that works directly with this graph representation, and computes the minimum number of semesters necessary to complete the curriculum (assume that a student can take any number of courses in one semester). The running time of your algorithm should be linear.

3.17. Infinite paths. Let G = (V, E) be a directed graph with a designated “start vertex” s ∈ V , a set VG ⊆ V of “good” vertices, and a set VB ⊆ V of “bad” vertices. An infinite trace p of G is an infinite sequence v 0 v 1 v 2 · · · of vertices vi ∈ V such that (1) v 0 = s, and (2) for all i ≥ 0 , (vi, vi+1) ∈ E. That is, p is an infinite path in G starting at vertex s. Since the set V of vertices is finite, every infinite trace of G must visit some vertices infinitely often.

(a) If p is an infinite trace, let Inf (p) ⊆ V be the set of vertices that occur infinitely often in p. Show that Inf (p) is a subset of a strongly connected component of G. (b) Describe an algorithm that determines if G has an infinite trace. (c) Describe an algorithm that determines if G has an infinite trace that visits some good vertex in VG infinitely often. (d) Describe an algorithm that determines if G has an infinite trace that visits some good vertex in VG infinitely often, but visits no bad vertex in VB infinitely often.

3.18. You are given a binary tree T = (V, E) (in adjacency list format), along with a designated root node r ∈ V. Recall that u is said to be an ancestor of v in the rooted tree, if the path from r to v in T passes through u. You wish to preprocess the tree so that queries of the form “is u an ancestor of v?” can be answered in constant time. The preprocessing itself should take linear time. How can this be done?

3.19. As in the previous problem, you are given a binary tree T = (V, E) with designated root node. In addition, there is an array x[·] with a value for each node in V. Define a new array z[·] as follows: for each u ∈ V ,

z[u] = the maximum of the x-values associated with u’s descendants. Give a linear-time algorithm which calculates the entire z-array.

3.20. You are given a tree T = (V, E) along with a designated root node r ∈ V. The parent of any node v 6 = r, denoted p(v), is defined to be the node adjacent to v in the path from r to v. By convention, p(r) = r. For k > 1 , define pk^ (v) = pk−^1 (p(v)) and p^1 (v) = p(v) (so pk(v) is the kth ancestor of v). Each vertex v of the tree has an associated non-negative integer label l(v). Give a linear-time algorithm to update the labels of all the vertices in T according to the following rule: lnew (v) = l(pl(v)(v)).

3.21. Give a linear-time algorithm to find an odd-length cycle in a directed graph. ( Hint: First solve this problem under the assumption that the graph is strongly connected.)

110 Algorithms

3.22. Give an efficient algorithm which takes as input a directed graph G = (V, E), and determines whether or not there is a vertex s ∈ V from which all other vertices are reachable.

3.23. Give an efficient algorithm that takes as input a directed acyclic graph G = (V, E), and two vertices s, t ∈ V , and outputs the number of different directed paths from s to t in G.

3.24. Give a linear-time algorithm for the following task.

Input: A directed acyclic graph G Question: Does G contain a directed path that touches every vertex exactly once?

3.25. You are given a directed graph in which each node u ∈ V has an associated price pu which is a positive integer. Define the array cost as follows: for each u ∈ V ,

cost[u] = price of the cheapest node reachable from u (including u itself).

For instance, in the graph below (with prices shown for each vertex), the cost values of the nodes A, B, C, D, E, F are 2 , 1 , 4 , 1 , 4 , 5 , respectively.

A

B

C

D

E

F

1 5

2 6 4

3 Your goal is to design an algorithm that fills in the entire cost array (i.e., for all vertices).

(a) Give a linear-time algorithm that works for directed acyclic graphs. ( Hint: Handle the vertices in a particular order .)

(b) Extend this to a linear-time algorithm that works for all directed graphs. ( Hint: Recall the “two-tiered” structure of directed graphs.)

3.26. An Eulerian tour in an undirected graph is a cycle that is allowed to pass through each vertex multiple times, but must use each edge exactly once. This simple concept was used by Euler in 1736 to solve the famous Konigsberg bridge problem, which launched the field of graph theory. The city of Konigsberg (now called Kaliningrad, in western Russia) is the meeting point of two rivers with a small island in the middle. There are seven bridges across the rivers, and a popular recreational question of the time was to determine whether it is possible to perform a tour in which each bridge is crossed exactly once. Euler formulated the relevant information as a graph with four nodes (denoting land masses) and seven edges (denoting bridges), as shown here.