Finish LCS, Greedy Algorithms




CS146

Chris Pollett

Apr 28, 2014

Outline

Introduction

Step 1: Characterizing an LCS

Step 2: A Recursive Solution

Step 3: Computing the length of an LCS

LCS-Length

LCS-LENGTH(X,Y)
01 m = X.length
02 n = Y.length
03 let b[1..m, 1 ..n] and c[0..m, 0..n] be new tables
04 for i = 1 to m //initialize first column
05    c[i, 0] = 0
06 for j = 0 to n //initialize first row
07    c[0, j] = 0
08 for i = 1 to n
09    for j = 1 to m
10       if X[i] == Y[j]
11           c[i,j] = c[i-1, j -1] + 1
12           b[i,j] = "diagonal"
13       elseif c[i-1,j] ≥ c[i, j - 1]
14           c[i,j] = c[i-1,j]
15           b[i,j] = "up"
16       else c[i,j] = c[i, j-1]
17           b[i,j] = "left"
18 return c and b

This procedure will be `Theta(mn)` because of the doubly nested for loop each step of which takes `Theta(1)` time to compute.

Step 4: Constructing an LCS

PRINT-LCS(b, X, i, j)
1 if i == 0 or j == 0
2    return //empty sequence is an LCS
3 if b[i,j] == "diagonal"
4    PRINT-LCS(b, X, i - 1, j - 1)//print sub-case first so forward order
5    print x[i]
6 elseif b[i,j] == "up"
7    PRINT-LCS(b, X, i - 1, j)
8 else PRINT-LCS(b, X, i, j - 1)

Example

Example computing the LCS of ABCBDAB and BDCABA

Quiz (Sec 5)

Which of the following statements is true?

  1. The run-time of the non-dynamic programming version of CUT-ROD presented in class was `O(n^3)`.
  2. A problem exhibits optimal substructure if optimal solutions to a problem incorporate optimal solutions to related subproblems, which can be solved independently.
  3. The LCS of two strings is always unique.

Quiz (Sec 6)

Which of the following statements is true?

  1. When deleting a node from an RB-tree, we run the BST algorithm, color the root red and do rotations down the tree until we get to the place where the deletion occurred.
  2. The bottom-up, dynamic programming solution to CUT-ROD did not make use of an auxiliary array for memory.
  3. One can see the optimal substructure property of LCS by considering the last character of the two strings we are trying to compute LCS for.

Greedy Algorithms

The Activity-Selection Problem

Example

Example Activity Selector Table

Optimal Substructure

Dynamic Programming Solution to Activity-Selector

Making Greedy Choices