Solutions to Hw5

advertisement
CS 3345 – Spring 2012
Homework 5 Solutions
Q1. We will find the longest distance travelled away from every vertex and report back the
largest number. The following algorithm will accomplish this and the analysis follows.
Algorithm: findDiameter(T)
Input: a tree T
Output: the length of the longest path between two vertices
Pseudocode:
diameter  0
for all v ∈ T do
T1  BFS(T, v)
for all w such that w ≠ v do
if distance(v, w) > diameter then
diameter  distance(v, w)
return diameter
This algorithm runs in O(n(n + m)) time. For each of the n vertices in T, breadth-first search will
run in O(n + m) time. Since T is a tree, it follows that m = n – 1. Thus, the algorithm will run in
O(n(n + n – 1)) = O(n2) time.
Q2. If we think of the stations as vertices and the links as edges, we are basically just performing
a modified breath-first search to find the vertices that can be reached by at most 4 edges from the
vertex.
If we are given a graph in which every vertex is at most 3 edges away from any other vertex, we
would be performing n complete BFS traversals, which gives a worst case run time of O(n(n +
m) time.
Q3. This strategy does not always work. Consider the following graph as a counter-example:
1
a
20
b
10
start
10
30
40
10
goal
15
c
Using the above algorithm, the vertices are visited in the order start, a, c, goal, for a total path
length of 30. However, the shortest path from start to goal is through the vertex c; that is, start
 c  goal for a total path length of 25.
Q4.
3
b
d
7
-5
c
starta
12
Q5. By contradiction: Let T be a minimum spanning tree of a graph G (with distinctly weighted
edges) generated by Kruskal’s algorithm. Assume that T’ is another minimum spanning tree for
G. Now, suppose e is the first edge of T which does not belong to T’. We denote by C the cycle
in T’ + e that contains e and f to be an edge of C which is not in T’. Thus, by Kruskal’s
algorithm, it follows that the weight of f must be greater than the weight of e. If weight(f) <
weight(e), then Kruskal’s algorithm would have called for tree of weight less than T’, and from
this it follows that T’ is not a minimum spanning tree for G. Hence, this is a contradiction.
2
Download