Docsity

U.C. Berkeley CS170 Midterm 2: Algorithms Exam, Exams of Algorithms and Programming

Partial preview of the text

Download U.C. Berkeley CS170 Midterm 2: Algorithms Exam and more Exams Algorithms and Programming in PDF only on Docsity!

U.C. Berkeley – CS170: Algorithms Midterm 2 Lecturers: Umesh Vazirani & Christos Papadimitriou April 1, 2004

Midterm 2

Name:

TA:

Answer all questions. Read them carefully first. Be precise and concise. The number of points indicate the amount of time (in minutes) each problem is worth spending. Write in the space provided, and use the back of the page for scratch. Good Luck!

total

Problem 1

(20 points)

In the graph shown above: (a) In what order are the vertices deleted from the priority queue in Dijkstra’s algorithm for the shortest path? (Start node: A.)

(b) In Prim’s algorithm for the minimum spanning tree? (Start node: A.)

(c) In what order are the edges added in Kruskal’s algorithm?

(d) show the union-find trees at the end of Kruskal’s algorithm (in case of a tie in rank, the lexicographically first node becomes root).

  1. (3 points) Suppose all edge weights are different. Then the shortest path from A to B is unique.
  2. (3points) There is an efficient algorithm for finding the longest (highest length) path in a dag.
  3. (3 points) There is an efficient algorithm for finding the longest (highest length) path in a graph with only positive weights.
  1. (3 points) There is an efficient algorithm for finding longest (highest length) paths in a graph with only negative weights.
  2. (3 points) Any operation in the union-find data structure takes at most O(log n) time.
  3. (3 points) Even without path compression, any operation in the union-find data structure takes at most O(log n) time.
  4. (3 points) Any operation in the union-find data structure takes at most O(log* n) time.

Problem 4

(15 points) Given an array of integers a 1 ,a 2 ,…,an, positive and negative, such as -1, 3, 2, -7, 4, 2, -2, 3, -1, you want to find the largest sum of contiguous integers; in this case it would be 4 + 2 – 2 + 3 = 7.

We can accomplish this by (you guessed it!) dynamic programming. For each i = 0,…,n define maxsum[i] to be the value of the largest sum seen so far. We also need maxsuff[i] to be the largest sum of a suffix ending at ai. (In the array above, maxsum[4] = 5, maxsuff[4] = 0).

Fill in the blanks in the dynamic programming algorithm:

(a) initialize: maxsum[0] = maxsuff[0] =

(b) iteration: for i = 0, …, n-1, maxsum[i+1] =

maxsuff[i+1] =

(c) What other data structure do you need in order to recover in the end the beginning and end of the maximum contiguous sum?

(d) What is the running time of the algorithm?