Lecture 8 Notes

# 4expresstherecursiverelationtopdownthisstepisquitestra

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: max = 0 for i = 1 to n begin if w[i] <= W then begin var value = p[i] + knapsackr(p, w, n, W-w[i]) if max < value then max = value end end return max end (5) Use memoization to eliminate redundancy. In order to leverage memoization, we need to keep track of V (W ) . function knapsack(p, w, n, W) begin var max = 0 for cw = 1 to W begin var value = knapsackr(p, w, n, cw) if max < value then max = value end return max end var m = {0, -1, -1, …} function knapsackr(p, w, n, W) begin if m[W] = -1 then begin var max = 0 for i = 1 to n begin if w[i] <= W then begin var value = p[i] + knapsackr(p, w, n, W-w if max < value then max = value end end m[W] = max end return m[W] end (6) Express the recursive relation bottom­up. function knapsack(p, w, n, W) begin var V = {0, -1, -1, …} var gmax = 0 for cw = 1 to W begin var max = 0 for i = 1 to n begin if w[i] <= cw then begin var value = p[i] + V[cw-w[i]] if max < value then max = value end end V[cw] = max if gmax < V[cw] then gmax = V[cw] end return gmax end (7) Parallelize. Similar to “1. Fibonacci Number” parallelize strategy. 4. Shortest Path (Floyd–Warshall algorithm) Problem. Given a graph G=(V, E), solve all‐pairs shortest‐paths. Let’s assume V = {1, 2, …, n}, and the weight between vertex i and j to be w (i, j ) . (1) Find the recursive relation. In order to figure out the recursive relations let’s consider a subset {1, 2, …, k} of vertices. D(i, j ) k indicates the shortest path from i to j with all intermediate vertices in the set {1, 2, …, k}. We could develop our recursive relation by the following: ⎧ if k = 0 w(i, j ) D(i, j ) k = ⎨ k −1 k −1 k −1 ⎩min(D(i, j ) , D(i, k ) + D(k, j ) ) if k ≥ 1 (2) What is the answer of the problem? Because all intermediate vertices in any path should be in the set {1, 2, …, n}, the answer of the problem all‐pairs shortest‐ paths should be the matrix D n . (3) Try an example to verify the recursive relation. Let’s assume our graph G=(V, E) is the following. V={1, 2, 3, 4, 5}, E is expressed in w (i, j ) ‐ ∞ means no edge between vertex i and j. This example is from the “Introduction to Algorithms” book. ⎡ 0 3 8 ∞ −4⎤ ⎢ ⎥ ⎢∞ 0 ∞ 1 7 ⎥ w = ⎢∞ 4 0 ∞ ∞ ⎥ ⎥ ⎢ ⎢ 2 ∞ −5 0 ∞ ⎥ ⎢ ⎦ ⎣∞ ∞ ∞ 6 0 ⎥ He...
View Full Document

Ask a homework question - tutors are online