15-211 : Fundamental Data Structures and Algorithms SOLUTIONS

86 downloads 111 Views 33KB Size Report
1. Graph theory: Given a simple graph with V vertices and E edges. (a). (10). What is the worst-case runtime (in O-notation) of the BFS on a graph if adjacency.
15-211 Quiz 5

Page 1 of 5

15-211 : Fundamental Data Structures and Algorithms

SOLUTIONS

15-211 Quiz 5

Page 2 of 5

1. Graph theory: Given a simple graph with V vertices and E edges. (10)

(a) What is the worst-case runtime (in O-notation) of the BFS on a graph if adjacency matrix is used? Give the tightest bound. Solution: O(V 2 ). It takes O(V ) to find out all vertices adjacent to a chosen one.

(10)

(b) What is the worst-case runtime (in O-notation) of testing if an undirected graph contains a vertex that is not connected to other vertices, if the graph is represented as adjacency matrix? Give the tightest bound. Solution: O(V 2 ). See problem a).

(5)

(c) What is the worst-case complexity of Kruskal’s algorithm when disjoint sets are implemented with i. a linear array Solution: O(V ∗ E + E log E)

(5)

ii. a union-find algorithm Solution: O(E + E log E)amortized

(5)

(d) On what graphs (dense or sparse) will you run Prim’s or Kruskal’s algorithms? Explain your answer by providing the worst-case complexities. i. dense Solution: Prim’s O(V log V + E log V )

(5)

ii. sparse Solution: Kruskal’s O(E + E log E)

(10)

(e) Given G = {V, E}. Design an algorithm to test whether the graph is connected. What is its runtime complexity? Solution: DFS, O(V + E)

15-211 Quiz 5

Page 3 of 5

(20) 2. Kruskal’s algorithm: Use Kruskal’s algorithm to draw the minimum spanning tree of the graph below. List all edges in order they inserted into the tree

A 1 2

C 3 6 G

E

4

2

1

D

3

5 F

4 4

B 1

H

Solution: AC-FD-HB-AD-FE-CH-GH

A 1 2

C E

D

2

G

1

3 F 4 B 1 H

15-211 Quiz 5

Page 4 of 5

(30) 3. Dijkstra’s algorithm: Use Dijkstra’s algorithm to find the distances from vertex A to all other vertices of the graph below. Show in a table how the vertex labels (distances) change during the course of the algorithm. Draw a shortest path tree.

A 1 2

C 7 6 G

E

4

2

1

D

9

5 F

4 4

B 1

H

A

B

C

D

E

F

G

H

15-211 Quiz 5

Page 5 of 5

Solution: A 0

B ∞

C ∞

D ∞

1

2

E ∞

F ∞

8 7 0

7

1

2

6

3

5

3

A 1 2

C 6

E 2

G

D 1 5

F 4 H

B

G ∞

H ∞

7

10

7

7