$ \def\opt{ {\mathrm{opt}} } $
Homework 5 Posted
Input:
Output: A set $S$ of requests to service with
Idea. keep track of remaining budget
Definition. For $j = 0, 1, \ldots, n$, $\opt(j, C)$ is optimal value of set of requests from $1, 2, \ldots, j$ with budget $C$.
Recurrence relation:
$\opt(n, B) = \max(\opt(n - 1, B), v_n + \opt(n - 1, B - b_n))$
Assume. All durations $b_i$ are integers at most $B$.
Compute. To compute $\opt(n, B)$:
max
where max[j, C]
stores the value $\opt(j, C)$Initialization. max[j, 0] <- 0
for all j
Apply Recursion Relation.
max[j, C] <- Max(max[j-1, C], v[j] + max[j-1, C - b[j]])
FindMax(R, n, B):
max <- new 2d array of dimensions n+1, B+1
set max[0, C] <- 0 for C = 0 to B
for j from 1 to n
(b, v) <- i-th request in R
for C from 0 to B
if b <= C then
max[j, C] <- Max(v + max[j-1, C-b], max[j-1,C])
else
max[j, C] <- max[j-1, C]
return max[n, B]
Claim. For all $j$ and $C$, $\max[j, C] = \opt(j, C)$
Proof. Induction on $j$.
Base case $j = 0$. Optimal subset of size $0$ has value $0$.
Inductive step $j \implies j+1$.
request $j+1$ is in optimal subset $S$
$\opt(j+1, C) = v_{j+1} + \opt(j, C - b_{j+1}) = v_{j+1} + \max[j, C - b_{j+1}]$
request $j+1$ is not in optimal subset $S$
$\opt(j+1, C) = \opt(j, C) = \max[j, C]$
FindMax(R, n, B):
max <- new 2d array of dimensions n+1, B+1
set max[0, C] <- 0 for C = 0 to B
for j from 1 to n
(b, v) <- i-th request in R
for C from 0 to B
if b <= C then
max[j, C] <- Max(v + max[j-1, C-b], max[j-1,C])
else
max[j, C] <- max[j-1, C]
return max[n, B]
For the knapsack problem with $n$ requests and budget $B$, we can find compute $\opt(n, B)$ in $O(B n)$ time.
How similar are the following strings?
For how many indices do the strings disagree?
How could we transform one string into the other?
Given two strings/arrays $X$ and $Y$ form a matching between characters
Rules for matching:
Given a matching $M$ between strings $X$ and $Y$
Total penalty is sum of individual penalties
Example.
Input:
Output:
Suppose
Claim. Then one of the following holds:
Why?
Idea. Use previous claim to give recursive characterization of optimal alignment.
How?
Define
Question. What is a recurrence relation for $\opt(i, j)$?
Construct a two dimensional array p[0..n, 0..m]
p[i, j]
should store $\opt(i, j)$Question 1. How to initialize p
?
Question 2. How to fill out p
?
Alignment(X, Y, a, d):
p <- 2d array of dimension (n+1) x (m+1)
for i from 0 to n, p[i, 0] <- i * d
for j from 0 to m, p[0, j] <- j * d
for i from 1 to n
for j from 1 to m
unmatchX <- p[i-1, j] + d
unmatchY <- p[i,j-1] + d
match <- p[i-1,j-1]
if X[i] != Y[j] then match <- match + a
p[i, j] <- Min(unmatchX, unmatchY, match)
return p[n, m]
Running time?
Optimal alignment between strings can be found in $O(n m)$ time where strings have lengths $n$ and $m$, respectively.
Shortest paths, revisited