0% found this document useful (0 votes)
10 views11 pages

MIT6_006S20_q2_sol

Uploaded by

fovav31082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views11 pages

MIT6_006S20_q2_sol

Uploaded by

fovav31082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Introduction to Algorithms

Massachusetts Institute of Technology 6.006 Spring 2020


Instructors: Erik Demaine, Jason Ku, and Justin Solomon Solution: Quiz 2

Solution: Quiz 2
• Do not open this quiz booklet until directed to do so. Read all the instructions on this page.
• When the quiz begins, write your name on the top of every page of this quiz booklet.
• You have 90 minutes to earn a maximum of 90 points. Do not spend too much time on any
one problem. Skim them all first, and attack them in the order that allows you to make the
most progress.
• You are allowed two double-sided letter-sized sheet with your own notes. No calculators,
cell phones, or other programmable or communication devices are permitted.
• Write your solutions in the space provided. Pages will be scanned and separated for grading.
If you need more space, write “Continued on S1” (or S2, S3) and continue your solution on
the referenced scratch page at the end of the exam.
• Do not waste time and paper rederiving facts that we have studied in lecture, recitation, or
problem sets. Simply cite them.
• When writing an algorithm, a clear description in English will suffice. Pseudo-code is not
required. Be sure to argue that your algorithm is correct, and analyze the asymptotic
running time of your algorithm. Even if your algorithm does not meet a requested bound,
you may receive partial credit for inefficient solutions that are correct.
• Pay close attention to the instructions for each problem. Depending on the problem,
partial credit may be awarded for incomplete answers.

Problem Parts Points


1: Information 2 2
2: Exact Edges 1 16
3: Color Cost 1 18
4: Orkscapade 1 18
5: Count Cycles 1 18
6: Bellham’s Fjord 1 18
Total 90

Name:

School Email:
2 6.006 Solution: Quiz 2 Name

Problem 1. [2 points] Information (2 parts)

(a) [1 point] Write your name and email address on the cover page.
Solution: OK!

(b) [1 point] Write your name at the top of each page.


Solution: OK!
6.006 Solution: Quiz 2 Name 3

Problem 2. [16 points] Exact Edges


Given a weighted, directed graph G = (V, E, w) with positive and negative edge weights, and
given a particular vertex v ∈ V , describe an O(k|E|)-time algorithm to return the minimum weight
of any cycle containing vertex v that also has exactly k edges, or return that no such cycle exists.
Recall that a cycle may repeat vertices/edges.
Solution: Assume all vertices in G are reachable from v so that |V | = O(|E|); otherwise, run
BFS or DFS to solve single source reachability from v, and replace G with the subgraph reachable
from v in O(|E|) time. Construct a new graph G0 = (V 0 , E 0 ) with:
• k + 1 vertices for each vertex v ∈ V : specifically vi for all i ∈ {0, . . . , k}; and
• k edges for each edge (u, v) ∈ E: specifically edges (ui−1 , vi ) for all i ∈ {1, . . . , k}.
Graph G0 has (k + 1)|V | = O(k|E|) vertices and k|E| edges in k + 1 layers, and has the property
that paths from v0 to vk have a one-to-one correspondence with cycles through v in G of the same
weight containing exactly k edges, since exactly one edge is traversed with each increase in layer.
So solve SSSP from v0 in G0 to return the minimum weight path to vk . Since edges in G0 always
increase in subscript, G0 is a DAG, so we can solve SSSP using DAG relaxation in linear time with
respect to the size of G0 . So together with initial pruning, this algorithm takes O(k|E|) time in
total.
Common Mistakes:

• Using BFS to detect cycles in a directed graph (need DFS)


• Trying to enumerate all paths or cycles of length k (may be exponential)
• Using Bellman-Ford without removing zero-weight edges (may use fewer than k edges)
• Finding cycles using k − 1 edges, not k edges
• Trying to find negative-weight cycles (wrong problem)
• Not running a reachability algorithm to prune to graph reachable from v
4 6.006 Solution: Quiz 2 Name

Problem 3. [18 points] Color Cost


A 3-color labeling of a graph maps each edge to either red, green, or blue. The color cost of a
3-color labeled path is its path weight plus a positive integer wc every time the path changes color.
For example, in the graph below (having four vertices {a, b, c, d}, a blue edge (a, b) with weight w1 ,
a red edge (b, c) with weight w2 , and another blue edge (c, d) with weight w3 ) the path (a, b, c, d)
has color cost w1 + w2 + w3 + 2wc , because the path changes color twice.

w1 w2 w3
a b c d

Given a 3-color labeling c : E → {red, green, blue} of a connected, weighted, undirected graph
G = (V, E, w) containing only positive edge weights, and given two vertices s, t ∈ V , describe
an efficient algorithm to return a path from s to t having minimum color cost.
(By “efficient”, we mean that faster correct algorithms will receive more points than slower ones.)
Solution: Construct a new graph G0 = (V 0 , E 0 ) with:
• 3 vertices for each vertex v ∈ V : specifically vi for i ∈ {red, green, blue} corresponding to
arriving at vertex v via an edge with color i;
• (vertex-edges) 3 undirected edges for each vertex v ∈ V : specifically {vred , vblue }, {vgreen , vred },
and {vblue , vgreen } of weight wc ; and
• (edge-edges) 1 undirected edge for each undirected edge {u, v} ∈ E of weight w and color
c(u, v): specifically undirected edge {uc(u,v) , vc(u,v) } with weight w.
Graph G0 has 3|V | vertices and 3|V | + |E| edges, and has the property that the minimum weight
of any path in G0 from any vertex si to any vertex tj for i, j ∈ {red, green, blue} is equal to the
minimum color cost of any 3-color labeled path in G from s to t, as switching colors at a vertex
requires traversing an edge of weight wc . So solve SSSP three times, once from each vertex si and
find the minimum weight of any path to any tj , and then return a minimum path by constructing
parent pointers as shown in lecture. Since this graph only has positive edge weights, we can solve
SSSP using Dijkstra in O(|V | + |E| + |V | log |V |) = O(|E| + |V | log |V |) time.
Note that you can avoid running Dijkstra three times via a supernode, but this only reduces work
by a constant factor. Also, one can also avoid adding vertex-edges by adding three edges for each
edge connected and weighted appropriately, but these edges will need to be directed toward a
vertex labeled with the same color as the corresponding edge.
Common Mistakes:

• Incorrectly trying to modify Dijkstra to keep track of state


• Failing to identify (or identifying incorrectly) a source from which to run SSSP
• Weighting or directing edges in a duplicated graph incorrectly
6.006 Solution: Quiz 2 Name 5

Problem 4. [18 points] Orkscapade


Ranger Raargorn needs to deliver a message from her home town of Tina’s Mirth to the town of
Riverdell, but the towns of Midgard have been overrun by an army of k Orks. Raargorn has a
map of the n towns and 3n roads in Midgard, where each road connects a pair of towns in both
directions. Scouts have determined the number of Orks ri ≥ 1 stationed in each town i (there is at
least one Ork stationed in each town). Describe an O(k)-time algorithm to find a path from Tina’s
Mirth to Riverdell on which Raargorn will encounter the fewest total Orks in towns along the way.
Partial credit will be awarded for slower correct algorithms, e.g., O(k log k) or O(nk).
Solution: Construct a graph G = (V, E) with:
• a chain of ri vertices (v1 , . . . , vrv ) connected by rv −1 edges for each town v, i.e., unweighted
directed edge (vi , vi+1 ) for all i ∈ {1, . . . , rv − 1}; and
• two unweighted directed edges (uru , v1 ) and (vrv , u1 ) for each road between towns u and v.
P P
Graph G has v rv = k vertices and 2(3n) + v (rv − 1) = 5n + k edges. Since there is at least
one Ork in each town, k ≥ n, so G has size O(k). Let s and t correspond to the towns of Tina’s
Mirth and Riverdell respectively. Graph G has the property that any path from s1 to trt corresponds
to a path from Tina’s Mirth to Riverdell crossing edges equal to the number of Orks encounters in
towns along the way, since for any road connecting towns u and v, going from u1 to v1 requires
traversing rv edges in G. So solve unweighted SSSP from s1 to trt using BFS in O(k) time, and
return the sequence of towns visited along the found shortest path by following parent pointers.
Common Mistakes:

• Not directing edges with vertex weight, or otherwise not clearly defining a graph
• Expanding weights on all edges, leading to an O(nk) expansion
• (e.g., a town with Θ(k) Orks may connect to Θ(n) roads)
• Using Dijkstra without modification to achieve an O(k log k)-time algorithm
• Expanding vertex weights incorrectly (path length ri instead of ri − 1)
• Finding shortest paths in a BFS or DFS tree (may not contain shortest paths)
6 6.006 Solution: Quiz 2 Name

Problem 5. [18 points] Count Cycles


A cycle-sparse graph is any weighted directed simple graph G = (V, E, w) for which every vertex
v ∈ V is reachable from at most one simple1 negative-weight cycle in G. Given a cycle-sparse
graph, describe an O(|V |3 )-time algorithm to return the number of negative-weight cycles in G.
Solution: Construct a new graph G0 by adding a supernode x to G with a zero-weight directed
edge (x, v) for each v ∈ V . Then run SSSP from x in G0 using Bellman-Ford to label each vertex
v ∈ V with its shortest path distance δ(x, v). For each v ∈ V , δ(x, v) = −∞ if and only if v is
reachable from a negative-weight cycle in G (since adding x does not add or remove any cycles).
Further, for any directed edge (u, v), if δ(x, u) = δ(x, v) = −∞, then both u and v are each
reachable from the same simple negative-weight cycle (since v is reachable from u and each vertex
is reachable from at most one simple negative-weight cycle).
So, construct a new graph G00 on only the vertices v ∈ V where δ(x, v) = −∞ in G0 , with an
undirected edge between u and v in G00 if they share a directed edge in G. Graph G00 has the
property that the number of connected components in G00 equals the number of negative-weight
cycles in G, so count and return the number of connected components in G00 using Full-BFS or
Full-DFS. This algorithm takes O(|V | + |E|) time to construct G0 , O(|V ||E|) time to run Bellman-
Ford, O(|V |+|E|) time to construct G00 , and then O(|V |+|E|) time to count connected components
in G00 , leading to an O(|V ||E|) = O(|V |3 ) running time in total.
Common Mistakes:

• General lack of precision when describing algorithm


• Trying to enumerate all paths or cycles (may be exponential)
• Repeatedly running Bellman-Ford, generally yielding |V | · O(|V ||E|) = O(|V |4 ) time
• Stating that |E| = O(|V |)
• Confusing connected components with strongly connected components

1
Recall a cycle is simple if visits any vertex at most once.
6.006 Solution: Quiz 2 Name 7

Problem 6. [18 points] Bellham’s Fjord


Gralexandra Bellham wants to drive her electric car in Norway from location s in Oslo to a scenic
Fjord at location t. She has a map of the n locations in Norway and the O(n) one-way roads
directly connecting pairs of them.
• Each location x is marked with its (positive or negative) integer height h(x) above sea-level.
• Her car has regenerative braking allowing it to generate energy while going downhill. Each
road from location x to y is marked with the integer energy J(x, y) that the electric car will
either spend (positive) or generate (negative) while driving along it.
• By the laws of physics, J(x, y) is always strictly greater than the difference in potential
energy between locations x and y, i.e., J(x, y) > m · g · (h(y) − h(x)), where m and g are
the mass of the car and the acceleration due to gravity respectively.
Her car battery has very large energy capacity b > 2nk where k is the maximum |J(x, y)| of any
road. Assuming she departs s at half capacity, bb/2c, describe an O(n log n)-time algorithm to
determine the maximum amount of energy Bellham can have in her battery upon reaching t.
Partial credit will be awarded for slower correct algorithms, e.g., O(n2 ).
Solution: Construct graph G with a vertex for each of the n locations in Norway and a directed
edge for each of the O(n) roads: specifically for each road from location u to v, add directed edge
(u, v) weighted by J(u, v). Then bb/2c minus the weight of a minimum-weight path from s to t
in G would correspond to the maximum energy Bellham could have upon reaching t; or at least it
would be if she did not either exceed or exhaust her tank along the way.
First we show that every minimum-weight path from s to t in G is simple. It suffices to show that
Pk directed cycleP
every in G has positive weight. Consider cycle (c0 , . . . , ck−1 , ck = c0 ). C has weight
k
i=1 J(ci−1 , ci ) > i=1 mg(h(ci ) − h(ci−1 )) = 0, as desired.

Any simple path in G traverses at most n − 1 edges, so the magnitude of its weight is at most
(n − 1)k < b/2. Thus bb/2c minus the weight of any simple path in G will always be > 0 and < b
(so Bellham cannot exhaust or exceed her tank by driving on a simple path from s to t).
Lastly, we find the weight of a minimum-weight path from s to t by solving SSSP. Unfortunately
using Bellman-Ford takes O(n2 ) time which is too slow. However, we can re-weight edges in G to
be positive while preserving shortest paths by exploiting the provided vertex potentials, similar to
Johnson’s algorithm. Specifically, create new graph G0 , identical to G, except change the weight
of each edge (u, v) to J(u, v) − mg(h(v) − h(u)) > 0. This transformation preserves shortest
paths since the weight of each path from, e.g., a to b changes by the same amount, namely by
mg(h(b) − h(a)). So run Dijkstra from s to find the minimum weight D of any path to t in G0 , and
return bb/2c − (D − mg(h(b) − h(a))).
Constructing G takes O(n) time, reweighting to G0 also takes O(n) time, and then running Dijkstra
from s in G0 takes O(n log n) time, leading to O(n log n) time in total.
Common mistakes continued on S1.
8 6.006 Solution: Quiz 2 Name

SCRATCH PAPER 1. DO NOT REMOVE FROM THE EXAM.

You can use this paper to write a longer solution if you run out of space, but be sure to write
“Continued on S1” on the problem statement’s page.

Common Mistakes: (for Problem 6)

• Using Bellman-Ford directly yielding O(n2 )-time algorithm (eligible for half the points)
• Running Bellman-Ford to find new weights, still leading to O(n2 )-time
• Using −J on weights instead of J
• b-times graph duplication (inefficient, b may be much larger than n)
6.006 Solution: Quiz 2 Name 9

SCRATCH PAPER 2. DO NOT REMOVE FROM THE EXAM.

You can use this paper to write a longer solution if you run out of space, but be sure to write
“Continued on S2” on the problem statement’s page.
10 6.006 Solution: Quiz 2 Name

SCRATCH PAPER 3. DO NOT REMOVE FROM THE EXAM.

You can use this paper to write a longer solution if you run out of space, but be sure to write
“Continued on S3” on the problem statement’s page.
MIT OpenCourseWare
https://ocw.mit.edu

6.006 Introduction to Algorithms


Spring 2020

For information about citing these materials or our Terms of Use, visit: https://ocw.mit.edu/terms

You might also like