The following code solves the recurrence by filling a table \(M[\cdot]\).
M[1] ← 0
for i ← 2 to n do {
M[i] ← ∞
for k ← 1 to i-1 do
M[i] ← min(M[i], M[k]+C[k,i])
}
Suppose the cost function \(c(\cdot,\cdot)\) is given as the following 2d-array of numbers
2 | 3 | 4 | 5 | 6 | 7 | |
---|---|---|---|---|---|---|
1 | 100 | 200 | 300 | 400 | 500 | 600 |
2 | 50 | 100 | 150 | 200 | 300 | |
3 | 60 | 100 | 115 | 240 | ||
4 | 40 | 70 | 100 | |||
5 | 40 | 40 | ||||
6 | 20 |
The filled-in table \(M\) then looks like this
i | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|
M[i] | 0 | 100 | 150 | 200 | 240 | 265 | 280 |
In order to find the corresponding route, we can record the minimizers in a table as we are filling in the \(M[\cdot]\) table, like so:
i | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|
M[i] | 0 | 100 | 150 | 200 | 240 | 265 | 280 |
K[i] | 1 | 2 | 2 | 4 | 3 | 5 |
Question: What is curious about the cheapest way to fly to city 6?
We can print the cheapest route with a simple recursive algorithm.
/* print out the cheapest route from 1 to k, starting at city 1 */
stops(k) {
if k = 1 then
print 1
else {
stops(K[k])
print k
}
}
stops(n)
.The running time for printing out the cheapest route is \(O(n)\).