$ \def\opt{ {\mathrm{opt}} } $
Given strings $X$ and $Y$ form a matching between characters
Rules for matching:
Input:
Output:
Suppose
Claim. Then at least 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.
Adjacency List
Single Source Shortest Paths (SSSP):
Input:
Output:
Question. What if edge weights can be negative?
Assume. $G$ does not contain any negative weight cycles.
Why?
Claim. $G$ a graph with $n$ vertices, $u, v$ vertices in $G$. If $G$ does not contain negative weight cycles, then the shortest (weighted) path from $u$ to $v$ contains at most $n-1$ edges.
Why?
Suppose shortest path from $u$ to $x$ contains $j$ hops.
Idea. For each vertex $v$ and each $j = 1, 2, \ldots, n-1$ compute $d_j(u, v) = $ length of shortest path from $u$ to $v$ with at most $j$ hops.
Question 1. How to initialize $d_0(u, v)$?
Question 2. Given $d_j(u, v)$ for all v, how to find $d_{j+1}(u, v)$?
Bellman-Ford(V, E, w, u)
d <- 2d array [0..n-1, 1..n]
for v = 1 to n do d[0, v] <- infinity
d[0, u] <- 0
for j = 1 to n-1 do
for each vertex v in V set d[j, v] <- d[j-1,v]
for each vertex v in V
for each neighbor x of v
d[j, x] <- Min(d[j, x], d[j-1, v] + w[v, x])
return d[n-1]
Running time?
Network Flow!