Docsity

Homework 1 for Algorithm Design Basics | CMSC 451, Assignments of Computer Science

Toggle sidebar
bg1
CMSC 451:Spring 2008 Dave Mount
Homework 1: Algorithm Design Basics
Handed out Thu, Feb 7. Due at the start of class Tue, Feb 19. Late homeworks are not accepted, but you
may drop your lowest homework score.
References: For reference information on asymptotics, summations, and recurrences, see either the text,
by Cormen, Leiserson, Rivest, and Stein or the text by Kleinberg and Tardos. Also see the class handout on
Background Information.
Notation: Throughout the semester, we will use lg xto denote logarithm of xbase 2 (log2x) and ln xto
denote the natural logarithm of x. We will use log xwhen the base does not matter.
Problem 1. The eminent but flaky Professor Hubert J. Farnsworth1proposed the following simpler algo-
rithm for the stable marriage problem. As in the standard problem, there are nmen and nwomen,
and each man and each woman has an n-element preference list that orders all the members of the
opposite sex.
(1) Repeat the following for irunning from 1 to n:
(a) Man miproposes to the highest woman on his preference list.
(b) This woman accepts this proposal, and is immediately removed from the preference lists of
all remaining men.
(2) Output the resulting sets of mates.
(Note that in his algorithm, once a woman accepts a man’s proposal, she will never break it off.) We
will explore the correctness of Farnsworth’s algorithm by answering the following questions.
(a) Is the matching produced by Farnsworth’s algorithm guaranteed to be stable? If so, give a proof.
If not, present a counterexample. (See the note below.)
(b) Suppose that all the woman in this system have exactly the same sets of preferences, and in
particular, they rank the men in (decreasing preference) order hm1, m2,...,mni. The men’s
preferences are not constrained. (Of course, each man’s list must contain all the women.) Under
this restriction, is the matching produced by Farnsworth’s algorithm guaranteed to be stable? As
before, either give a proof or present a counterexample.
(Throughout the semester, whenever you are asked to present a counterexample, you should strive
to make your counterexample as short and clear as possible. In addition to giving the input for the
counterexample, briefly explain what the algorithm does when run on this input and why it is wrong.)
Problem 2. Consider the following summation, which holds for all n≥0,
n
X
i=1
i3= n
X
i=1
i!2
That is (13+ 23+···+n3) = (1 + 2 + ···+n)2.
(a) Prove this identity holds for all n≥0, by induction on n. (Recall that by convention, for n= 0
we have an empty sum, whose value is defined to be the additive identity, that is, zero.)
(b) The following figure provides an informal “pictorial proof” of this identity. Explain why.
1Famous inventor of the Coolometer, a hand-held device that measures a persons “coolness” as measured in “MegaFonzies.”
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Homework 1 for Algorithm Design Basics | CMSC 451 and more Assignments Computer Science in PDF only on Docsity!

CMSC 451:Spring 2008 Dave Mount

Homework 1: Algorithm Design Basics

Handed out Thu, Feb 7. Due at the start of class Tue, Feb 19. Late homeworks are not accepted, but you may drop your lowest homework score.

References: For reference information on asymptotics, summations, and recurrences, see either the text, by Cormen, Leiserson, Rivest, and Stein or the text by Kleinberg and Tardos. Also see the class handout on Background Information.

Notation: Throughout the semester, we will use lg x to denote logarithm of x base 2 (log 2 x) and ln x to denote the natural logarithm of x. We will use log x when the base does not matter.

Problem 1. The eminent but flaky Professor Hubert J. Farnsworth^1 proposed the following simpler algo- rithm for the stable marriage problem. As in the standard problem, there are n men and n women, and each man and each woman has an n-element preference list that orders all the members of the opposite sex.

(1) Repeat the following for i running from 1 to n: (a) Man mi proposes to the highest woman on his preference list. (b) This woman accepts this proposal, and is immediately removed from the preference lists of all remaining men. (2) Output the resulting sets of mates.

(Note that in his algorithm, once a woman accepts a man’s proposal, she will never break it off.) We will explore the correctness of Farnsworth’s algorithm by answering the following questions.

(a) Is the matching produced by Farnsworth’s algorithm guaranteed to be stable? If so, give a proof. If not, present a counterexample. (See the note below.) (b) Suppose that all the woman in this system have exactly the same sets of preferences, and in particular, they rank the men in (decreasing preference) order 〈m 1 , m 2 ,... , mn〉. The men’s preferences are not constrained. (Of course, each man’s list must contain all the women.) Under this restriction, is the matching produced by Farnsworth’s algorithm guaranteed to be stable? As before, either give a proof or present a counterexample.

(Throughout the semester, whenever you are asked to present a counterexample, you should strive to make your counterexample as short and clear as possible. In addition to giving the input for the counterexample, briefly explain what the algorithm does when run on this input and why it is wrong.)

Problem 2. Consider the following summation, which holds for all n ≥ 0,

∑^ n

i=

i^3 =

( (^) n ∑

i=

i

That is (1^3 + 2^3 + · · · + n^3 ) = (1 + 2 + · · · + n)^2.

(a) Prove this identity holds for all n ≥ 0, by induction on n. (Recall that by convention, for n = 0 we have an empty sum, whose value is defined to be the additive identity, that is, zero.) (b) The following figure provides an informal “pictorial proof” of this identity. Explain why.

(^1) Famous inventor of the Coolometer, a hand-held device that measures a persons “coolness” as measured in “MegaFonzies.”

Figure 1: Problem 2.

Problem 3. For each of the parts below, list the functions in increasing asymptotic order. In some cases functions may be asymptotically equivalent (that is f (n) is Θ(g(n))). In such cases indicate this by writing f (n) ≡ g(n). When one is asymptotically strictly less than the other (that is, f (n) is O(g(n)) but f (n) is not Θ(g(n))), express this as f (n) ≺ g(n). For example, given the set:

n^2 n log n 3 n + n log n,

the answer would be n log n ≡ 3 n + n log n ≺ n^2. Explanations are not required, but may be given to help in assigning partial credit. (Hint: Review Chapt. 3 in CLRS, especially the section on logarithms.)

(a) (3/2)n^3 (n/2)^2 (n/3) (b) lg n ln n lg(n^2 ) (c) nlg 4^2 lg^ n^2 (2 lg^ n) (d) max(50n^2 , n^3 ) 50 n^2 + n^3 min(50n^2 , n^3 ) (e)

n^2 / 20

n^2 / 20

n^2 / 20

Problem 4. The purpose of this problem is to design a more efficient algorithm for the previous larger element problem, as introduced in class. Recall that we are given a sequence of numeric values, 〈a 1 , a 2 ,... , an〉. For each element ai, for 1 ≤ i ≤ n, we want to know the index of the rightmost element of the sequence 〈a 1 , a 2 ,... , ai− 1 〉 whose value is strictly larger than ai. If no element of this subsequence is larger than ai then, by convention, the index will be 0. Here is naive the Θ(n^2 ) algorithm from class.

previousLarger(a[1..n]) { for (i = 1 to n) j = i-1; while (j > 0 and a[j] <= a[i]) j--; p[i] = j; } return p }

There is one obvious source of inefficiency in this algorithm, namely the statement j--, which steps through the array one element at a time. A more efficient approach would be to exploit p-values that have already been constructed. (If you don’t see this right away, try drawing a picture.) Using this insight, design a more efficient algorithm. For full credit, your algorithm should run in Θ(n) time. Prove that your algorithm is correct and derive its running time.

CMSC 451:Spring 2008 Dave Mount

Homework 2: BFS, DFS, and Greedy Algorithms

Handed out Thu, Feb 21. Due at the start of class Tue, Mar 4. Late homeworks are not accepted, but you may drop your lowest homework score.

As always, if you are asked to present an algorithm, in addition to the algorithm you must justify its correctness and derive its running time.

Problem 1. Consider the BFS algorithm presented in class. Given a digraph G = (V, E) and a starting vertex s ∈ V , this algorithm computes for each vertex u ∈ V the value d[u], which is the length (number of edges) on the shortest path from s to u. For purposes of robust network communications, it is sometimes useful to know the number of shortest paths. The objective of this problem is to modify the BFS algorithm of class to compute the number of shortest paths from s to each vertex of G. We will do this in two steps.

(a) First run the standard BFS on G, starting from s. Explain how to use the result of this BFS to produce a new digraph G′^ = (V ′, E′), where V ′^ ⊆ V and E′^ ⊆ E, such that every path in G′ that starts at s, is a shortest path in G starting from s, and conversely, every shortest path in G starting from s is a path in G′. (b) Explain how to take the result of part (a) to compute for each vertex u ∈ V ′, a quantity c[u], which is the number of paths in G′^ from s to u. (Hint: This can be done by a modification of BFS.)

Both of your algorithms should run in O(V + E) time. Hint: Be careful in how you compute c[u]. In general, the number of shortest paths from one node to another can be exponential in the size of V. (You might think about why this is.) This means that your algorithm cannot generate the paths one by one. Rather, it must employ some method that can count up many paths at once.

Problem 2. Each of the following problems involves knowledge of cycles and paths in undirected and directed graphs. For all three parts, assume that the graph or digraph is represented using an adjacency list.

(a) Present an algorithm which, given an undirected graph G = (V, E), determines whether G contains a cycle in O(V ) time. (It is important that the running time of your algorithm is independent of E, which may generally be as high as Ω(V 2 ).) (b) The eminent but flaky Professor Hubert J. Farnsworth^1 claims that he has discovered an O(V ) time algorithm that determines whether a digraph has a cycle, assuming that the digraph is represented using a standard adjacency list. Prove that the Professor is wrong! Hint: Assume that you have the professor’s source code. Based on his code and given an arbitrary value V for the number of vertices, devise an digraph with Ω(V 2 ) edges, with the property that if his algorithm fails to look at every edge of your graph, you can trick his algorithm into producing the wrong result by altering one of the edges that his algorithm failed to look at. (c) A digraph G = (V, E) is said to be semi-connected if, given any two vertices, u, v ∈ V , there exists a path from u to v, or there exists a path from v to u, but not necessarily both. Give an algorithm which, given a directed acyclic graph (DAG), determines whether it is weakly connected. (^1) Noted inventor of the electric frankfurter and winner of the Academy of Sciences award for “Advances in superconductivity properties of sandwich meats.”

Problem 3. The following two problems involve algorithms for connectivity in graphs and digraphs.

(a) Recall that a bridge is an edge in a connected, undirected graph whose removal causes the graph to become unconnected. Present an O(V + E) algorithm, which reports all the bridges in a graph. (b) The concept of a bridge can be extended to directed graphs. (I don’t know that it has any particular name, so I’ll make one up.) Given a digraph G = (V, E), an edge (u, v) is called a span if there is no path from v to u in G. Present an O(V + E) algorithm, which determines all the tree edges of the DFS forest that are spans. (Note that cross edges and forward edges might be spans as well, but your algorithm should only report on the DFS tree edges that are spans.)

Hint: Both algorithms can be implemented by an appropriate modification of the algorithm we gave in class for biconnected components.

a

i

h

f

d

b

e

a c

g

i

h

f

d

b

e

c

g

(a) (b)

Figure 1: Problem 3(a) and 3(b). Bridge edges (shown as bold lines) in (a) are {d, g}, {f, h}, and {e, f }. Span edges (shown in bold in (b)) are (c, g), (d, g), (d, f ), (b, e), and (e, f ).

Problem 4. Consider a long straight road with houses scattered very sparsely along its length. Let x 1 < x 2 <... < xn denote the locations of these houses. Design a greedy algorithm that will place the minimum number of cell towers along this road so that every house is within four miles of one of the towers. (Your algorithm should run in O(n) time.) Prove that the result it produces is optimal. (Try to be rigorous in your proof, for example, by showing that any optimal solution that is not equal to the greedy solution can be converted into a solution of equal size that is closer to the greedy solution, in some sense.)

x 1 x 2 x 3 x 4 x 5 x 6 x 7

head neck

shoulder

hip

front feet rear feet Problem 4 Challenge Problem

Challenge Problem. Challenge problems count for extra credit points. These additional points are fac- tored in only after the final cutoffs have been set, and can only increase your final grade. Given integers i and j, both greater than or equal to 2, we define an (i, j)-goat to be an undirected graph which consists of n = i + j + 4 vertices. The vertices consist of i front feet, j rear feet, and four extra vertices, the head, the neck, the shoulder, and the hip. These are connected as shown below (head-neck-shoulder-hip, and front feet to shoulder and rear feet to hip) (see the figure above). You are given the n × n adjacency matrix for an n-vertex goat, but you are not told what the values of i and j are. Give an O(n) time algorithm which, given the adjacency matrix of a goat, determines the

CMSC 451:Spring 2008 Dave Mount

Homework 3: Kruskal, Dijkstra, and Dynamic Programming

Handed out Tue, Mar 11. Due at the start of class Thu, Mar 27. Late homeworks are not accepted, but you may drop your lowest homework score.

As always, if you are asked to present an algorithm, in addition to the algorithm you must justify its correctness and derive its running time.

Problem 1. Suppose that you wish to route flow through a network of pipes. We model the network as a connected, undirected graph G = (V, E), in which each edge has a numeric value c(u, v), which repre- sents the edge’s capacity, that is, the amount of flow it can take. Given any path P = 〈u 1 , u 2 ,... , uk〉, its capacity is defined to be the minimum capacity of any edge on the path, that is cap(P ) = min(c(u 1 , u 2 ), c(u 2 , u 3 ),... , c(uk− 1 , uk)). By convention, c(u, u) = ∞. For every u, v ∈ V , define cap(u, v) to be the maximum capacity over all paths from u to v.

(a) (Single-Source Capacity) Given a source vertex s ∈ V , present an algorithm that computes cap(s, u) for all u ∈ V. Your algorithm should run in O(E log V ) time. (Hint: One solution that I know of involves modifying Dijkstra’s algorithm.) (b) (All-pairs capacity) Present an algorithm that computes cap(u, v) for all u, v ∈ V. Your algorithm should run in O(V 3 ) time. (Hint: One solution that I know of involves modifying the Floyd- Warshall algorithm.)

In both cases it is sufficient just to compute the capacity of the paths. It is not required to compute the actual paths. Note: In both cases, be sure to establish the correctness of your algorithms. It is not sufficient to simply appeal to the correctness of related algorithms like Dijkstra’s or Floyd-Warshall. Capacity is fundamentally a different optimization criterion than weighted path length, and so the proofs of these other algorithms will need to be modified to work in this context.

Problem 2. On the planet of Smurf, the adorable, gentle Smurf folk hold a convention every four years. In case you don’t know, Smurf’s never die, and they are all descended from a common ancestor, the venerable “Papa Smurf.” It is ancient Smurf tradition that for every father-son pair at least one of the two must attend the convention, and both may attend. This means that, if a Smurf decides to stay home, his father and all his children are required to attend. Assume that you are given n Smurfs, named Smurf-1 through Smurf-n. For 1 ≤ i ≤ n, let Ti denote the travel cost of sending Smurf-i to the convention. You may assume the Smurfs have been numbered, so that if Smurf-i is the father of Smurf-j, then i < j. (Thus, Papa Smurf is Smurf-1.) Give an algorithm to determine (1) the minimum total travel costs for all the Smurfs, subject to the above attendance requirement, and (2) output the set of Smurfs attending the convention (see Fig. 1). The inputs to your algorithm are two arrays C and T , where C[i] is the list of the children of Smurf-i, and T [i] is the associated travel cost. Derive the running time of your algorithm. (O(n) time is possible.) For example, in Figure 1, we give a sample example. The distances are listed next to each node of the Smurf family tree. The optimal solution is to send Smurfs 1 and 2 to the meeting, for a total transportation cost of 5.2 + 7 = 12.2. Hint: I know a few different solutions. One involves dynamic programming and another is a greedy solution. You are free to present any O(n) time algorithm. In any case, be sure to show your algorithm’s correctness.

1

2

3 4 5

6

7

1 2 3.

5.2 12.

C[1] = [2, 6] C[2] = [3, 4, 5] C[3] = [ ] C[4] = [ ] C[5] = [ ]

1

2

3 4 5

6

7

1 2 3.

5.2 12.

Input Optimal Solution

C[6] = [ ]

Figure 1: Example for Problem 2. Next to each node of the tree is its travel cost.

Problem 3. In this problem we will consider two variations of the longest common subsequence problem. You are given three sequences X, Y , and Z, where m = |X|, n = |Y | and |Z| = k. You want to know whether the sequences X and Y can be shuffled together (without changing the relative order of elements within either sequence) in order to form the sequence Z. For example, if X = 〈ABC〉, Y = 〈BACA〉, and Z = 〈ABBACCA〉 the answer is “yes,” (Z = 〈AxBxBy Ay CxCy Ay 〉) but if Z = 〈ABCBAAC〉 the answer is “no.” You may assume that k = m + n, for otherwise answer is definitely “no.”

(a) The eminent but flaky Professor Hubert J. Farnsworth^1 claims that the following simple algorithm works for this problem. First, compute the LCS of X and Z, and remove these elements from Z. Let Z′^ be the resulting sequence. If Y = Z′^ then the answer is yes, and otherwise, the answer is no. Is Farnsworth’s algorithm correct? Either prove that it is or present a counterexample. (b) Present an O(nm) time algorithm that answers this decision problem. (Whether right or wrong, you cannot reuse Farnsworth’s algorithm.) (c) Let us convert this decision problem into an optimization problem, by computing the smallest number of deletions from any of X, Y , or Z to make such a shuffle possible. For example, if X = 〈ABC〉, Y = 〈BACA〉, and Z = 〈ABCBAAC〉, then by deleting the last character of Y and the second to last character of Z, such a shuffle is possible. Thus, the answer would be 2. The running time of your algorithm should be O(mnk) where m = |X|, n = |Y |, and k = |Z|. (Because characters can be deleted, you should not assume that that k = m + n.) Your algorithm should not only compute the minimum number of deletions needed, but it should also output the set of deletions to be performed.

Problem 4. A pizza delivery boy needs to make a series of deliveries. He is given the coordinates pi = (xi, yi) of a collection of n points {p 1 , p 2 ,... , pn}. You may assume that the points are given in increasing order of x-coordinate, that is, x 1 < x 2 <... < xn. His pizza parlour is located at p 1 , and his route is subject to the restriction that he first travels strictly from left to right (along increasing x-coordinates) until getting to pn, and then he returns to p 1 strictly from right to left (along decreasing x-coordinates). (See Fig. 2.) Present an efficient algorithm that computes the cost of the shortest delivery tour that visits all the points subject to the above left-right-left restriction. (You do not need to compute the path, just the cost.) You may assume that you have access to a function dist(i, j), which returns the distance from point pi to pj. Hint: Use DP. Rather than thinking of a outbound and inbound path, consider a formulation that builds two paths, both starting at p 1 and both traveling from left to right, such that each point will either be added to one path or the other. In my formulation, I used two variables i and j, where one path ended at point i and the other ended at point j. For full credit, your algorithm should run in O(n^2 ) time. I suspect that there is a somewhat simpler O(n^3 ) time algorithm. (^1) Noted inventor of the nose tuba, a brass instrument that can be played with the nose. The nose tuba achieved notoriety as the only musical instrument to be featured in an article of the International Journal of the Medical Malpractice, because of its tendency to cause musicians to blow their brains out while attempting the tricky second movement of Mendelssohn’s Tuba Concerto in A minor.

CMSC 451:Spring 2008 Dave Mount

Homework 4: Network Flow and NP-Completeness

Handed out Tue, Apr 15. Due at the start of class Tue, Apr 29. Late homeworks are not accepted, but you may drop your lowest homework score.

As always, if you are asked to present an algorithm, in addition to the algorithm you must justify its correctness and derive its running time.

Problem 1. The eminent but flaky Professor Hubert J. Farnsworth^1 has invented an alternative network flow algorithm. His algorithm is similar to Ford-Fulkerson, but Farnsworth’s algorithm only increases flows along edges that have not yet reached their capacity—it never reduces flow on any edge by pushing flow along backward edges of the residual network.

  • (For partial credit) Show that Farnsworth’s algorithm is not optimal by presenting a coun- terexample, which consists of an s-t network G such that his algorithm terminates with a flow that is strictly less than the true maximum flow. You are free to select the augmenting paths however you like in forming your counterexample.
  • (For full credit) Show that Farnsworth’s algorithm is not merely suboptimal but can be arbi- trarily bad. In particular, given any positive integer b > 1, show how to construct an s-t network G such that the ratio between the true maximum flow in G to Farnsworth’s flow at least as large as b. (The size of your network and its capacities are allowed to be functions of b.)

Be sure to explain how your counterexample works.

Problem 2. Describe a polynomial time algorithm for the following problem. You are given a flow network G = (V, E) with source s and sink t, and whose edges all have unit capacity, that is, c(u, v) = 1 for all (u, v) ∈ E. Your algorithm is also given a parameter k (1 ≤ k ≤ |E|). The objective is to delete k edges from G so as to reduce the maximum s-t flow value as much as possible. In other words, compute a subset E′^ ⊆ E of size k such that the flow in G′^ = (V, E − E′) is as low as possible. Justify your algorithm’s correctness and derive its running time.

Problem 3. You are the manager of the computing staff at Mega State University, and one of your less pleasant duties involves assigning your staff to be on-call during holiday periods. There are n people in your staff and there are m holiday periods. Based on your calendar, you know that the jth holiday runs for d[j] days. (You may assume that no two holidays overlap in time.) Here are the constraints that you must abide by:

  • There must be one staff member on-call during every day of every holiday period.
  • According to union rules, no staff member may be on-call for more than c total days over all the holiday periods.
  • According to union rules, no staff member may be on-call for more than one day during any one holiday period.
  • Each staff member 1 ≤ i ≤ n has given you a list H[i] of holiday periods when they are available. (You may assume that if a person is listed as available for some holiday, he/she is available for any day of the holiday period.)

Describe a polynomial time algorithm, which given d[1..m], c, and H[1..n], generates an assignment of staff members to holidays. If no such assignment is possible, your algorithm should indicate this. Prove the correctness of your algorithm and give its running time. (^1) Famous inventor of the laser-guided ketchup dispenser, a device capable of squirting ketchup to within 2.5 microns of any desired spot on your hamburger. (The GPS-enabled version cannot be sold to minors, except in Texas.)

Problem 4. Consider a standard instance of the network flow algorithm, that is, an s-t network G = (V, E), where each edge (u, v) has a nonnegative integer capacity c(u, v). Present a polynomial time algorithm which determines whether G’s minimum s-t cut is unique. For example, the network shown in Fig. 1 has two distinct minimum cuts, each of capacity 11.

(a) (b)

s (^) t

a

c

e

u

v

x

2 5

6

4 3

2

(^33)

1 9

4 7

6

5

s (^) t

a

c

e

u

v

x

2 5

6

4 3

2

(^33)

1 9

4 7

6

5

Figure 1: A network with (at least) two distinct minimum s-t cuts, each of value 11.

Justify your algorithm’s correctness and derive its running time. Hint: One approach involves invoking a network flow algorithm as a black-box (either applied to G directly or to some modification of G) followed by a subsequent analysis of the flow and/or the residual network. This process may be repeated a number of times.

Problem 5. This problem involves the observation that a solution to a decision problem can often be used to solve a related optimization problem. Given an undirected graph G = (V, E), it is said to be 3-colorable if there is an assignment of the labels { 1 , 2 , 3 } to the vertices of G such that no two adjacent vertices have the same label. (It is known that deciding 3-colorability is an NP-complete problem.) Suppose that (by some miracle) you have access to a procedure is3Colorable(G) which, given an undirected graph G, returns true if G is 3-colorable and false otherwise. Using this procedure as a black box, present an algorithm which, given a undirected graph G determines whether G is 3-colorable, and if so outputs a valid coloring of the vertices. Your algorithm should run in polynomial time, and can make a polynomial number of calls to is3Colorable. Hint: Consider how to make a series of modifications to the graph which successively restrict the possible ways of choosing colors, but without changing the fact that G is 3-colorable.

Challenge Problem. Some friends of yours who watch lots of movies have invented a new game. You start with a set X of n actresses and a set Y of n actors, and two players P 0 and P 1. Player P 0 names an actress x 1 ∈ X, player P 1 names an actor y 1 ∈ Y who has appeared in a movie with x 1 , player P 0 then names an actress x 2 who has appeared in a movie with y 1 , and so on. Thus, P 0 and P 1 collectively generate a sequence 〈x 1 , y 1 , x 2 , y 2 ,.. .〉 such that each actor/actress in the sequence has appeared with the actress/actor immediately preceding. A player Pi (i = 0, 1) loses when it is Pi’s turn to move, and he/she cannot name a member of his/her set who has not been named before. Suppose you are given a specific pair of such sets X and Y , with complete information on who has appeared in a movie with whom. A strategy for player Pi, in our setting, is an algorithm that takes a current sequence 〈x 1 , y 1 , x 2 , y 2 ,.. .〉 and generates a legal next move for Pi (assuming it is Pi’s turn to move). Give a polynomial-time algorithm that decides which of the two players can force a win, in a particular instance of this game. Hint: The material from Section 7.5 of KT on bipartite matchings, and Hall’s Theorem in particular, may be useful.

Figure 1: Problem 5.

Challenge Problem. The local video store has received a shipment consisting of a large number of video tapes. Among these is one special tape. Exactly 7 days after viewing this tape the viewer dies a mysterious death without warning or exception. (This might remind you of a scary movie, which came out a number of years ago.) The video store manager wants to determine which of the tapes is the deadly one before the big sale coming up 8 days from now. He has managed to find a number of foolish people, who are willing to test the tapes for a hefty fee. Each tester will be given some subset of the tapes to view on the first day, and then he/she nervously waits for 7 days for the final results to develop. (There is no limit on the number of tapes that may be assigned to one tester, and each tape may be viewed many different testers.) Suppose that there are n tapes total. The manager realizes that he can determine the deadly tape by arranging for n testers, each of whom will view one tape. A smart clerk informs him that he can do it with fewer testers. What is the minimum number of tape testers needed to determine which tape is deadly and how is the test conducted? (The stingy store manager does not care how many of the testers dies in the process; he just wants to pay the least number of testers.) If the deadly tape is random among the set of n tapes, then what is the expected number of testers that survive the process?

CMSC 451:Spring 2008 Dave Mount

Practice Problems for the Midterm

The midterm will be on Tues, Apr 1. The exam will be closed-book and closed-notes, but you will be allowed one cheat-sheet (front and back).

Disclaimer: These are practice problems, which have been taken from old homeworks and exams. They do not necessarily reflect the actual length, difficulty, or coverage for the exam. For example, we have covered some topics this year that were not covered in previous semesters. So, just because a topic is not covered here, do not assume it will not be on the exam.

Problem 0. You should expect one problem in which you will be asked to work an example of one of the algorithms we have presented in class on a short example.

Problem 1. Short answer questions.

(a) Consider the code a = 〈 0 〉, b = 〈 01 〉, c = 〈 11 〉, d = 〈 101 〉. Is this a prefix code? Explain. (b) Consider a breadth-first search (BFS) of a directed graph G = (V, E). Let (u, v) be any edge in G. Is it possible that d[v] ≥ d[u] + 2? Explain briefly. (c) As a function of n, give an exact closed-form solution (no embedded sums) to the following summation:

T (n) =

∑^2 n

i=n

i.

(d) In the DFS of a digraph there is an edge (u, v) such that d[u] < d[v]. What are the possible types of this edge? (tree, back, forward, cross.) (e) Given a connected undirected graph G = (V, E) in which all edges have weight 1, what is the fastest and simplest way (that we know of) for computing a minimum spanning tree for G? (f) What is the maximum number of edges in an undirected graph with n vertices, in which each vertex has degree at most k? (g) You are given a graph with V vertices and E edges as an adjacency list. How fast can you sort the vertices in increasing order of their degrees? (Explain briefly.) (h) True or False: If a digraph has k distinct cycles, then for any depth-first search (DFS) of this digraph, there are at least k back edges.

Problem 2. Given two strings, X = x 1 x 2... xm and Y = y 1 y 2... yn, the shortest common supersequence (SCS) is a minimum length string Z such that both X and Y are subsequences of Z. For example, if X = 〈ABCBABA〉 and Y = 〈BCAABAB〉, then Z = 〈ABCAABABA〉 is an SCS of both X and Y. Give an O(mn) dynamic programming algorithm which given X and Y computes the length of the SCS of X and Y. You do not need to determine the actual SCS, just its length. Be sure to give the DP formulation, and explain its correctness. (Hint: There is a cute, tricky solution. But to gain practice in doing DP problems, even if you see it, work through the full DP formulation anyway.)

Problem 3. A pharmacist has W pills and n empty bottles. Let {p 1 , p 2 ,... , pn} denote the number of pills each bottle can hold.

(a) Describe a greedy algorithm, which given W and the pi’s determines the fewest number of bottles needed to store all the pills. (An informal description is sufficient.) (b) Argue that the first bottle chosen by your greedy algorithm will be in some optimal solution. (c) How would you modify your algorithm if each bottle also has an associated cost ci, and you want to minimize the total cost of the bottles used to store all the pills? (No need to prove correctness.)

CMSC 451:Spring 2008 Dave Mount

Midterm Exam

This exam is closed-book and closed-notes. You may use one sheet of notes (front and back).

Write all answers in the exam booklet. You may use any algorithms or results given in class. If

you have a question, either raise your hand or come to the front of class. Total point value is 100

points. Good luck!

Problem 1. (15 points)

Show the execution of Dijkstra’s shortest path algorithm on the digraph in

the figure, where s is the source vertex. Indicate each of the following:

(a) The order in which the vertices are removed from the priority queue,

(b) The final distance value d[u] for each vertex u,

(c) The final predecessor pointer pred[u] for each vertex u.

s 1 t

v u

2

3

9

(^68)

Problem 2. (30 points; 4–7 points each.) Short answer questions. Explanations are not always

required, but may be given for partial credit.

(a) List the following functions in increasing asymptotic order. (No explanations required.)

f (n) = nlg 8^ g(n) = 2 (2 lg^ n)^ h(n) = (min(n, 2))^5.

If two functions are asymptotically equal (e.g., if f (n) = Θ(g(n))), then indicate this.

(Recall that lg denotes logarithm base 2.)

(b) Recall that a digraph G = (V, E) is semi-connected if, given any two vertices, u, v ∈ V ,

there exists a path from u to v, or there exists a path from v to u, but not necessarily

both. Suppose you are given a semi-connected DAG G. True or false: The topological

ordering of the vertices of G is unique. Explain briefly.

(c) Suppose that you run DFS on a directed graph G = (V, E) and compute both discovery

and finish times for each vertex. For some edge (u, v) you observe that f [v] < d[u].

What type of edge might this be? (List all the apply. Give a short explanation.)

(i) tree edge (ii) back edge (iii) forward edge (iv) cross edge

(d) You are given a connected, undirected graph G = (V, E) with positive edge weights.

You form another graph G′^ by squaring the weight of every edge of G. True or false: A

spanning tree T is a minimum spanning tree of G if and only if T is a minimum spanning

tree of G′. Explain briefly.

(e) Recall the following two rules used in the Floyd-Warshall algorithm for computing short-

est paths in a directed graph with edge weights w(i, j).

d

(0)

ij =^ w(i, j)^ d

(k)

ij =^ min

d

(k−1)

ij , d

(k−1)

ik +^ d

(k−1) kj

Explain how to modify these rules for the following related problem. (You do not need

to modify the entire algorithm, just the rules.) For each edge (i, j) ∈ E you are given the

probability 0 < p(i, j) < 1 that the edge is usable. The probability that a path is usable

is the product (i.e., multiplication) of the probabilities of the edges on the path. For

each i and j, the objective of your algorithm is to compute the path whose probability

of usability is maximimum.

Problem 3. (20 points) Professor Farnsworth drives from College Park to Miami Florida along

I-95. He starts with a full tank and can go for 100 miles on a full tank. Let x 1 < x 2 <... < xn

denote the locations of the various gas stations along the way, measured in miles from College

Park. Present an algorithm that determines the fewest number of gas stations he needs to

stop at to make it to Miami without running out of gas along the way. Give a short proof of

the correctness.

0 x 1 x 2 x 3 x 4 x 5 x 6 xn− College Park

xn Miami

Problem 4. (20 points) For each of the following two problems, present a short algorithm, briefly

justify its correctness and derive its running time. (If you present a DP solution, it is sufficient

to present the recursive DP formulation, rather than an entire algorithm.)

(a) Consider the following modification of the longest common subsequence (LCS) problem.

You are given two strings X = 〈x 1 , x 2 ,... , xm〉 and Y = 〈y 1 , y 2 ,... , yn〉. The objective

is to compute the length of the longest common subsequence, in which each character

of X (but not Y ) is allowed to be repeated any number of times in the LCS.

A

A B C D B

B B C D B D D B C

X:

Y: A

A B C D B

BB C D D D B

B B C D B D D B C

X:

Y:

LCS(X,Y) with repetitions of X

Your program need only output the length of the LCS, not the actual subsequence.

(b) Consider a further modification. In addition to X and Y , you are give a positive integer

k. The problem is the same as in part (a), but each character of X can be repeated at

most k times in the final LCS. (Characters of Y cannot be repeated.)

For example, if k = 2 in the above figure, you would only be allowed to use ‘D’ twice,

rather than three times. (Hint: Add another index to your formulation of part (a).)

Problem 5. (15 points) You are given a connected undirected graph G = (V, E) in which each

edge’s weight is either 1 or 2. Present an O(V + E) time algorithm to compute a minimum

spanning tree for G. Explain your algorithm’s correctness and derive its running time. (Hint:

This can be done by a variant of DFS.)

Figure 1: A feedback vertex set (FVS) of size 2.

Problem 4. A tournament is a digraph G = (V, E) in which for each pair of vertices u and v, either there is an edge (u, v) or an edge (v, u) but not both. (See Fig. 2.) A directed Hamiltonian path is a path that visits every vertex in a digraph exactly once.

Figure 2: Hamiltonian path in a tournament.

(a) Prove that for all n ≥ 1, every tournament on n vertices has a directed Hamiltonian path. (Hint: Use induction on the number of vertices.) (b) Give an O(n^2 ) algorithm which given a tournament, finds a Hamiltonian path. (You may assume either an adjacency list or an adjacency matrix representation of G.)

Problem 5. Prove that the following problem, called the acyclic subgraph problem (AS) is NP-complete. Given a directed graph G = (V, E) and an integer k, determine whether G contains a subset V ′^ of k vertices such that the induced subgraph on V ′^ is acyclic. Recall that the induced subgraph on V ′^ is the subgraph G′^ = (V ′, E′) whose vertex set is V ′, and for which (u, v) ∈ E′^ if u, v ∈ V ′^ and (u, v) ∈ E. (Hint: Reduction from Independent Set. Think of a reduction that maps undirected edges to directed cycles.)

Problem 6. Show that the following problem is NP-complete. Remember to show (1) that it is in NP and (2) that some known NP-complete problem can be reduced to it. Balanced 3-coloring (B3C): Given a graph G = (V, E), where |V | is a multiple of 3, can G can be 3-colored such that the sizes of the 3 color groups are all equal to |V |/3. That is, can we assign an integer from { 1 , 2 , 3 } to each vertex of G such that no two adjacent vertices have the same color, and such that all the colors are used equally often. Hint: Reduction from the standard 3-coloring problem (3COL).

Problem 7. The set cover optimization problem is: Given a pair (X, S), where X is a finite set and a S = {s 1 , s 2 ,... , sn} is a collection of subsets of X, find a minimum sized collection of these sets C whose union equals X. Consider a special version of the set-cover problem in which each element of X occurs in at most three sets of S. Present an approximation algorithm for this special version of the set cover problem with a ratio bound of 3. Briefly derive the ratio bound of your algorithm

Problem 8. Prove that the Hamiltonian Path problem is NP-complete for undirected graphs. (Hint: Re- duction from Directed Hamiltonian Path. Replace each vertex with a small gadget that splits the incident edges into two groups, such that if a path enters from one group of edges then it must leave along the others.)