Fin f05 Sol
Fin f05 Sol
Final Solutions
1. Analysis of algorithms.
2. String searching.
3. hello
Pattern matching.
4. Convex hull.
(a) H G E F C D B A
(b) 1. I H
2. I H G
3. I H G E
4. I H G E F
5. I H C
6. I H C D
7. I H C B
8. I H C A
1
5. Geometry.
For simplicity, we assume no two endpoints have the same value.
(a) The 2N events are the left and right endpoints of each interval.
(b) To implement the sweep line, sort the endpoints and process in ascending order, say
using mergesort.
(c) Store the set of intervals intersecting the sweep line in a priority queue (say, a binary
heap), using the right endpoint as the key.
(d) • Left endpoint: insert the interval onto the PQ. Check the number of elements on
the PQ, if it is the most so far, record the x value of the current left endpoint.
• Right endpoint: perform a delete the min on the PQ. This removes the corresponding
interval from the PQ.
Note that the PQ isn’t strictly needed, since we could just increment a counter when pro-
cessing a left endpoint, and decrement it when processing a right endpoint.
(a) Preorder: A B C F D E G H I.
(b) Postorder: C F B E I H G D A.
(c) Topological: A D G H I E B F C.
2
7. Undirected graphs and BFS.
The key idea is that a shortest cycle is comprised of a shortest path between two vertices, say
v and w, that does not include edge v-w, plus the edge v-w. We can find the shortest such
path by deleting v-w from the graph and running breadth-first search from v (or w).
We run BFS E times and each run takes O(E + V ) time. The overall algorithm takes
O(E(E + V )) time.
Note that if you run BFS from s and stop as soon as you revisit a vertex (using a previously
ununused edge), you may not get the shortest path containing s. For example, in the following
graph, BFS might consider the edges s-1, s-2, s-3, 1-4, 2-4, thereby finding the cycle s-1-4-2-s
(instead of the shorter cycle s-2-3).
hello
3
8. Minimum spanning tree.
9. Data compression.
11. Reductions.
Create a new weighted digraph G0 as follows:
Observe that G has a Hamiltonian path if and only if G0 has a shortest simple path from s
to t of length exactly −(V + 1).