SlideShare a Scribd company logo
Programming Exam Help
Programming Exam Help
To get more info, Please
Visit : – https://www.programmingexamhelp.com/
E-Mail : – support@programmingexamhelp.com
Contact Us : – +1 678 648 4277
Problem 1. 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 , E0 ) 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)
Programming Exam Help
Problem 2. 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.
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 , E0 ) with:
Programming Exam Help
• 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
• 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.
Programming Exam Help
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
Problem 3.
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:
Programming Exam Help
• 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.
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)
Programming Exam Help
• Finding shortest paths in a BFS or DFS tree (may not contain shortest paths)
Problem 4. 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).
Programming Exam Help
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 BellmanFord, 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
Problem 5. 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.
Programming Exam Help
• 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
P every directed cycle in G has positive weight. Consider cycle (c0, . . . , ck-1, ck = c0). C has
weight k Pk J(ci-1, ci) > mg(h(ci) - h(ci-1)) = 0, as desired.
Programming Exam Help
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.
Programming Exam Help

More Related Content

PPT
B.tech admission in india
PDF
14 chapter9 graph_algorithmstopologicalsort_shortestpath
PPTX
Unit 2: All
PDF
Depth First Search and Breadth First Search
PDF
Graph applications chapter
PPTX
Graphs Algorithms
PPTX
Divergence,curl,gradient
PDF
B.tech admission in india
14 chapter9 graph_algorithmstopologicalsort_shortestpath
Unit 2: All
Depth First Search and Breadth First Search
Graph applications chapter
Graphs Algorithms
Divergence,curl,gradient

What's hot (19)

PDF
2 4 the_smith_chart_package
PPTX
Data structures and algorithms lab7
DOC
BFS, Breadth first search | Search Traversal Algorithm
PPT
Algorithm to count number of disjoint paths
PDF
Topological sorting
PDF
Day 5 application of graph ,biconnectivity fdp on ds
DOCX
G6 m3-c-lesson 17-t
PDF
Lesson 4: Lines and Planes (slides + notes)
PPT
Bfs
PPTX
Unit 9 graph
PPTX
Lecture 4 (27)
PPTX
Graphs data Structure
PPTX
Unit ix graph
PPTX
Shortest path problem
PPTX
Graphs
PPT
Graphs bfs dfs
PPT
Unit26 shortest pathalgorithm
PPT
Electromagnetic fields
PDF
Graph theory discrete mathmatics
2 4 the_smith_chart_package
Data structures and algorithms lab7
BFS, Breadth first search | Search Traversal Algorithm
Algorithm to count number of disjoint paths
Topological sorting
Day 5 application of graph ,biconnectivity fdp on ds
G6 m3-c-lesson 17-t
Lesson 4: Lines and Planes (slides + notes)
Bfs
Unit 9 graph
Lecture 4 (27)
Graphs data Structure
Unit ix graph
Shortest path problem
Graphs
Graphs bfs dfs
Unit26 shortest pathalgorithm
Electromagnetic fields
Graph theory discrete mathmatics
Ad

Similar to Programming Exam Help (20)

PPTX
Algorithm Exam Help
PPTX
Computer Science Assignment Help
PDF
Daa chpater14
PDF
Bellman Ford algorithm and shortest source path algorithm
PPT
chapter24.ppt
PPT
Graph theory
PPTX
GRAPH THEORY - Basic definition with examples
PPT
Graph theory presentation
PPTX
graph theory
PPTX
Graph ASS DBATU.pptx
PPTX
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
PPT
graph ASS (1).ppt
PPTX
Introduction to Graph-Theory.pptx
PPTX
Algorithms Design Exam Help
PPT
graphass1-23022111180722548-1ba6b00a.ppt
PPTX
Algorithms Design Assignment Help
PPTX
Lecture 4- Design Analysis Of ALgorithms
PPT
Inroduction_To_Algorithms_Lect14
PPT
Tn 110 lecture 8
PPT
Graphs in Data Structure
Algorithm Exam Help
Computer Science Assignment Help
Daa chpater14
Bellman Ford algorithm and shortest source path algorithm
chapter24.ppt
Graph theory
GRAPH THEORY - Basic definition with examples
Graph theory presentation
graph theory
Graph ASS DBATU.pptx
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
graph ASS (1).ppt
Introduction to Graph-Theory.pptx
Algorithms Design Exam Help
graphass1-23022111180722548-1ba6b00a.ppt
Algorithms Design Assignment Help
Lecture 4- Design Analysis Of ALgorithms
Inroduction_To_Algorithms_Lect14
Tn 110 lecture 8
Graphs in Data Structure
Ad

More from Programming Exam Help (20)

PPTX
Best Algorithms Design Exam Help
PPTX
Algorithm Exam Help
PPTX
Design and Analysis of Algorithms Exam Help
PPTX
Algorithm Exam Help
PPTX
Algorithms Exam Help
PPTX
Algorithms Exam Help
PPTX
Algorithms Exam Help
PPTX
Algorithms Design Exam Help
PPTX
Algorithms Exam Help
PPTX
Algorithms Exam Help
PPTX
Algorithm Exam Help
PPTX
C Exam Help
PPTX
Algorithm Exam Help
PPTX
C Exam Help
PPTX
Computer Science Exam Help
PPTX
Programming Exam Help
PPTX
Algorithm Exam Help
PPTX
Programming Exam Help
PPTX
Programming Exam Help
PPTX
Computer Science Exam Help
Best Algorithms Design Exam Help
Algorithm Exam Help
Design and Analysis of Algorithms Exam Help
Algorithm Exam Help
Algorithms Exam Help
Algorithms Exam Help
Algorithms Exam Help
Algorithms Design Exam Help
Algorithms Exam Help
Algorithms Exam Help
Algorithm Exam Help
C Exam Help
Algorithm Exam Help
C Exam Help
Computer Science Exam Help
Programming Exam Help
Algorithm Exam Help
Programming Exam Help
Programming Exam Help
Computer Science Exam Help

Recently uploaded (20)

PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
01-Introduction-to-Information-Management.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Sports Quiz easy sports quiz sports quiz
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Classroom Observation Tools for Teachers
PDF
Computing-Curriculum for Schools in Ghana
PDF
Complications of Minimal Access Surgery at WLH
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
Renaissance Architecture: A Journey from Faith to Humanism
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
01-Introduction-to-Information-Management.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Sports Quiz easy sports quiz sports quiz
VCE English Exam - Section C Student Revision Booklet
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O5-L3 Freight Transport Ops (International) V1.pdf
Microbial diseases, their pathogenesis and prophylaxis
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Classroom Observation Tools for Teachers
Computing-Curriculum for Schools in Ghana
Complications of Minimal Access Surgery at WLH
O7-L3 Supply Chain Operations - ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
human mycosis Human fungal infections are called human mycosis..pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
TR - Agricultural Crops Production NC III.pdf
Supply Chain Operations Speaking Notes -ICLT Program

Programming Exam Help

  • 1. Programming Exam Help Programming Exam Help To get more info, Please Visit : – https://www.programmingexamhelp.com/ E-Mail : – support@programmingexamhelp.com Contact Us : – +1 678 648 4277
  • 2. Problem 1. 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 , E0 ) 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) Programming Exam Help
  • 3. Problem 2. 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. 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 , E0 ) with: Programming Exam Help • 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. • 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. Programming Exam Help
  • 5. 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 Problem 3. 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: Programming Exam Help
  • 6. • 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. 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) Programming Exam Help
  • 7. • Finding shortest paths in a BFS or DFS tree (may not contain shortest paths) Problem 4. 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). Programming Exam Help
  • 8. 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 BellmanFord, 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 Problem 5. 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. Programming Exam Help
  • 9. • 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 P every directed cycle in G has positive weight. Consider cycle (c0, . . . , ck-1, ck = c0). C has weight k Pk J(ci-1, ci) > mg(h(ci) - h(ci-1)) = 0, as desired. Programming Exam Help
  • 10. 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. Programming Exam Help