Week 12
Week 12
Week 12
33.1 Introduction
• recall Dijkstra’s algorithm
finds minimal weight path from a single source
to all other vertices in a graph or digraph
• Dijkstra will not work for graphs with negative edges
explain that negative edges may be possible and reasonable
• Bellman-Ford will work for graphs with negative edges
33.2 An example
• develop algorithm using the following working example
• same example as shown on slides but there are errors there
uy zu
a 5 b
@ -2 6
@
6 @
@ -3
s uP
8 @
i @ 7
@ PPP @
@ PP
PP @ -4
@ PP 2 @
7 @ PP
PP @
@Ru
@ ? PP@
Pu
R
-
c 9
d
33.3
• use a table to show changes in estimates of distances and predecessors
• initialize table — no predecessors
ds da db dc dd
0 ∞ ∞ ∞ ∞
75
ds da db dc dd
Initially 0 ∞ ∞ ∞ ∞
After Pass 1 0 6, s 7, s
After Pass 2 0 4, c 2, a
After Pass 3 0 2, b
• show how we can use predecessor information to trace paths from source
76
34 Topological Sorting and Difference Constraints
34.1 Partial ordering
• examine the idea of a partial order briefly
• for a partial order ≺, we must have
∀a, a 6≺ a (irreflexive)
if a ≺ b and b ≺ c, then a ≺ c (transitive)
• an example
proper subsets
77
• vertex that has lowest departure time can be last in topological sort
why? — explain
t t
v1 0 v2
P P 1
6 @ PP
-1 @ PPP
0 PP 5
0 @ PP
t 0 q tv
@ 1 PP
v0 P P
-
@PPP
@
3
@4
@ 0 PPP
-3
P @
@ P
PPP@
0 -1
R t
@
@ )
PR t
@
q
P
v5 -3 v4
78
• to solve the system of inequalities, we apply Bellman-Ford to the graph
using v0 as the initial vertex
79
35 Hashing
35.1 Introduction
• a way of implementing the ADT dictionary
with operations
insert
search
delete
• excluding operations like
sort
largest
etc.
• hashing can provide a method that is O(1), (if we are careful)
• basic idea:
a place for everything and everything in its place
• analogy with students in class
insertion — people always choose the same seats
search — to see if somebody is in class, I only look in one place
80
35.3 Choosing a good hash function
• ideally, we would like to have each key equally likely to hash into any location
• not always possible but we can avoid some pitfalls
• sometimes plain keys show patterns
e.g. student numbers: 99. . .
e.g. Ontario driver’s licences: last six digits are birthdate
we sometimes use only some digits for key
• sometimes no numerical key
can convert characters to digits
• if we are using the division method, we must be careful of the array size
use a prime to avoid patterns
• to show why, consider using an array of size 100
now h(k) would depend only on last two digits of k
for driver’s licence, hash code would depend only on day of birth 01 to 31
• do an example
use an array of size 7
use h(k) = k (mod 7)
insert a sequence of values including some collisions
• usually we organize the linked lists as LIFO lists
this makes insertions easy
• if the lengths of the chains are kept fairly short
searching and deleting can be done quickly using a sequential search
81