Sunteți pe pagina 1din 8

CS 374

Midterm 2 Combined Solutions

Fall 2014

1. (= conflict problem 1) Clearly indicate the edges of the following spanning trees of the weighted graph
pictured below.
(a) A depth-first spanning tree rooted at s

Solution: There are many many different solutions; here are four.
s

(b) A breadth-first spanning tree rooted at s

Solution: There are exactly six correct solutions.


s

(c) A shortest-path tree rooted at s

Solution: The correct solution is unique.


4

3
4

3
6
2

5
2

4
7

(d) A minimum spanning tree.

Solution: The correct solution is unique.


4

3
4

5
2

7
1

Rubric: 2 points each. No credit for answers that are not spanning trees (disconnected, containing a cycle, or omitting a vertex). Otherwise, 1 for each edge-exchange
required to reach a correct solution; round negative scores up to 0. Vertex distances
are not required in part (c).

CS 374

Midterm 2 Combined Solutions

Fall 2014

2. Describe and analyze an algorithm to compute the largest number of chickens that Mr. Fox can earn by
running the obstacle course, given the array A[1 .. n] of booth numbers as input.

Solution: Let Chickens(i, r, d) denote the maximum number of chickens that Mr. Fox can earn
starting at the ith booth, assuming he just said Ring! r times in a row, or he just said Ding! d
times in a row. Notice that we must have either r = 0 or b = 0, and Boggis, Bunce, and Bens rules
imply that max r, b 3. We need to compute Chickens(1, 0, 0).
This function satisfies the following recurrence:

0
if i > n

Chickens(i + 1, 1, 0) + A[i]
if i n and d = 3

Chickens(i, r, d) = Chickens(i + 1, 0, 1) A[i]


if i n and r = 3

(
)

Chickens(i + 1, r + 1, 0) + A[i]

otherwise

max Chickens(i + 1, 0, d + 1) A[i]


We can memoize this function into an array Chickens[1 .. n, 1 .. 3, 1 .. 3]. Each entry Chickens[i, r, d]
in this array depends only on entries of the form Chickens[i + 1, r, d], we can fill this array in order
of decreasing i, filling in the 6 interesting entries Chickens[i, r, d] for each i in arbitrary order. The
resulting algorithm runs in O(n) time.

Rubric: Standard dynamic programming rubric.

CS 374

Midterm 2 Combined Solutions

Fall 2014

3. (= conflict problem 5) Describe and analyze an algorithm to determine whether a given collection of
predecessor pointers correctly defines a single-source shortest path tree.

Solution: Let T be the graph containing every vertex of G and every edge of the form (v, pred(v)).
We must verify three properties of this graph:
T is a subgraph of G. For each vertex v 6= s, scan through the list of vs neighbors for the
vertex pred(v). If we dont find pred(v) in vs neighbor list, return FALSE. This phase takes
O(E) time.
T is a spanning tree of G. Since T includes every vertex of G and V 1 edges by definition,
it suffices to check that T is connected. Run whatever-first search in T , starting at s. If the
search does not mark every vertex, return FALSE. This phase takes O(V ) time.
Every edge outside T is relaxed. Compute the distance in T from S to every other vertex using
a pre-order traversal of T . (To process any vertex v, set dist(v) dist(pred(v))+ w(pred(v), v)
and then recursively process each child of v.) Then for every edge uv 6 T , if we find that
|dist(u) dist(v)| > w(uv), return FALSE (because either u v or v u is tense). This phase
takes O(E) time.
Altogether, this algorithm runs in O(V + E) time.
Rubric: 10 points total:
2 for checking T is a subgraph of G .
2 for checking that T is a spanning tree of G .
2 for computing distances in T .
2 for checking that non-tree edges are relaxed.
2 for overall time analysis.

Max 8 points for O(E log V ) time (calling Dijkstra in T instead of WFS)
Max 6 points for O(EV ) time (calling Bellman-Ford in G to compute distances)
Max 5 points for slower (calling Dijkstra in G to compute distances)
This is not the only correct solution.
G may contain more than one shortest-path tree, so computing a shortest path tree
from scratch and comparing predecessor pointers is not enough.

CS 374

Midterm 2 Combined Solutions

Fall 2014

4. (= conflict problem 2) Describe and analyze an algorithm to find the index of the smallest element in a
given bitonic array in O(log n) time.

Solution: We use a variant of binary search. The key observation is that any subsequence of a
bitonic sequence is also bitonic, so if we can determine that the minimum element is in (say) the
left half of the input array, we can find it by recursively searching the left half.
MINBITONIC(A[1 .. n]):
l 1
rn
while r > l + 374
m b(l + r)/2c
if A[l] < A[m] < A[r]
jm
else if A[l] < A[r] < A[m]
jm
else if A[r] < A[l] < A[m]
im
else if A[r] < A[m] < A[l]
im
else if A[m] < A[r] < A[l]
jm
else if A[m] < A[l] < A[r]
im
compute min A[i .. j] by brute force

The algorithm runs in T (n) = O(1) + T (n/2) = O(log n) time.


Rubric: max 10 points = 2 for variant of binary search + 1 for base case + 6 for
recursive cases (= 1 for each permutation of A[l], A[m], A[r]) + 1 for time analysis.
Max 3 points for an O(n)-time algorithm. This is not the only correct solution, or even
the only correct way to describe this solution.

CS 374

Midterm 2 Combined Solutions

Fall 2014

5. Suppose we are given an undirected graph G in which every vertex has a positive weight.
(a) Describe and analyze an algorithm to find a spanning tree of G with minimum total weight.

Solution: Compute any spanning tree, using whatever-first search, in O(V + E) time. All
spanning trees have the same total weight.

Rubric: 3 points total = 2 for whatever-first search + 1 for time analysis. for
depth or breadth instead of whatever. 1 for Prim or Bor
uvka or Kruskal or
Dijkstra instead of whatever. 1 for regurgitating details of the traversal algorithm
instead of just writing whatever-first search.

(b) Describe and analyze an algorithm to find a path in G from one given vertex s to another given
vertex t with minimum total weight.

Solution: Let H be a directed graph obtained by replacing every undirected edge uv in G


with two directed edges u v and v u. Define the weight of each directed edge in H as the
weight of its head vertex in G; that is, w(u v) w(v). Finally, compute the shortest path
in H from s to t using Dijkstras algorithm. The entire algorithm runs in O(E log V) time.
Rubric: 7 points total =
+ 1 for defining vertices of H
+ 1 for defining edges of H
+ 2 for defining edge weights in H
+ 1 for computing shortest paths in H
+ 1 for calling Dijkstra
+ 1 for running time.
This is not the only correct answer.

CS 374

Midterm 2 Combined Solutions

Fall 2014

6. (= conflict problem 2) Describe and analyze an algorithm to determine if there is a walk in G from s to t
(possibly repeating vertices and/or edges) whose length is divisible by 3.

Solution (Build a different graph): Let G 0 = (V 0 , E 0 ) be the product of G and a directed cycle of
length 3; that is,
V 0 = V {0, 1, 2} = {(v, i) | v V and i {0, 1, 2}}.
E 0 = {(u, i)(v, (i + 1) mod 3) | u v E}.

The new graph G 0 has exactly three times as many vertices and edges as G.
We claim that G contains a walk from s to t whose length is a multiple of 3 if and only if G 0
contains a walk from (s, 0) to (t, 0). There are two claims to prove.
Suppose G contains a walk s v1  v2   v`1  t with length `. Then G 0 contains the
corresponding walk (s, 0)(v1 , 1) (v`1 , ` 1 mod 3)(t, ` mod 3). If ` is a multiple
of 3, the walk in G 0 ends at (t, 0).
Suppose G 0 contains a walk (s, 0)(v1 , 1) (v`1 , 2)(t, 0). The length of this walk must
be a multiple of 3, because any walk of length ` that starts at (s, 0), dropping the second
arguments from each vertex gives us a walk s v1  v2   v`1  t.

To solve the stated problem, we construct G 0 and then perform a whatever-first search starting at
(s, 0). If this search visits (t, 0), we return TRUE; otherwise, we return FALSE. Both the construction
and the graph traversal require O(V 0 + E 0 ) = O(V + E) time.

Solution (Build a different different graph (8/10)): Define a new graph G 0 = (V, E 0 ) whose
edges indicate paths of length 3 in G; that is,
E 0 = {wz | w x, x  y, y z E for some vertices x and y}.
There is a walk in G from s to t whose length is divisible by 3 if and only if there is a walk from s
to t in G 0 . We can construct E 0 in O(V E) time as follows:
CUBETHISGRAPH(V, E) :
E0
for all vertices w V
for all vertices x V
label(v) 0
for all edges w x E
label(x) 1
for all edges x  y E
if label(x) = 1
label( y) 2
for all edges y z E
if label( y) = 2
add wz to E 0
0
return E

Then we can find a walk from s to t to G 0 in O(V + E 0 ) = O(V 2 ) time using whatever-first search.
The overall algorithm runs in O(V E) time.

CS 374

Midterm 2 Combined Solutions

Fall 2014

Rubric: Standard graph modeling rubric. No proof of correctness is required. Max 8


points for O(V E) time; max 6 points for O(V 3 ) time; max 4 points for slower correct
algorithm; scale partial credit.
for writing breadth or depth instead of whatever. 1 for regurgitating
details of the traversal algorithm instead of just writing whatever-first search.
These are not the only correct solutions with the stated running times. In particular,
it is possible (but rather awkward) to modify any graph-traversal algorithm to mimic
these solutions without actually modifying the input graph.
The last time I posed this question on an exam, a fairly common mistake was to try
computing the lengths of all paths from s to t , and/or the lengths of all cycles reachable
from s, with a single linear-time traversal of the graph. But thats impossible; there are
far too many paths and cycles to enumerate them all in O(V + E) time. Whatever-first
search does NOT traverse all possible paths from s to t ; in fact, it traverses
exactly ONE such path. Many of the proposed algorithms would return the wrong
answer if the traversal chose the wrong path to t , which is possible even if the input
graph has no cycles.

CS 374

Midterm 2 Combined Solutions

Fall 2014

7. (= conflict problem 4) Describe and analyze an efficient algorithm to compute your maximum possible
score in Candy Swap Saga XIII.

Solution: Let MaxScore(i, c) be the maximum score I can earn starting at animal i holding candy
type c. This function satisfies the following recurrence:

MaxScore(i + 1, c) + 1

MaxScore(i, c) =

MaxScore(i + 1, c)

max
MaxScore(i + 1, c 0 ) 1

if i > n
if C[i] = c
if C[i] = c 0 6= c

We can memoize this function into an n 3 array. Since each entry MaxScore[i, c] depends only
on entries of the form MaxScore[i + 1, ], we can fill this array from right to left (decreasing i),
considering the three candy types in arbitrary order for each i. The resulting algorithm runs in
O(n) time.

Rubric: Standard dynamic programming rubric.

S-ar putea să vă placă și