Title: CS2420: Lecture 39
1CS2420 Lecture 39
- Vladimir Kulyukin
- Computer Science Department
- Utah State University
2Outline
- Graph Algorithms (Chapter 9)
3Priority Queue with Dynamic Updates
- Recall that a priority queue is a min (or max)
heap. - To implement Dijkstras algorithm, we need to
modify a standard priority queue to allow for
dynamic priority updates, because the dist member
variables of vertices (V.Dist) change dynamically
as we run the algorithm. - To allow for dynamic updates, we can have two
member variables in a priority queue class an
array of nodes (a hash table would do just as
well if we have a lot of nodes) and a heap of
nodes.
4Min Priority Queue Example
A
A
10
10
B
B
C
21
21
14
C
G
D
E
F
14
15
20
22
25
D
22
E
25
F
15
Priority Queue Hash Table Heap. Thus, we
implement a Min Priority Queue with 2 arrays 1
for the table 1 for the heap.
G
20
5Min Priority Queue Example
A
A
10
10
B
B
C
21
21
14
C
G
D
E
F
14
15
20
22
25
D
22
E
25
Suppose we want to update the priority of G
by changing it from 20 to 8.
F
15
G
20
6Min Priority Queue Example
A
A
10
10
B
B
C
21
21
14
C
G
D
E
F
14
15
8
22
25
D
22
E
25
F
Only 1 update is needed. Once we update the
priority in the hash table, the priority in the
heap is also updated, because it is THE SAME
POINTER stored in 2 arrays.
15
G
8
7Min Priority Queue Example
A
A
10
10
B
B
C
21
21
14
C
G
D
E
F
14
15
8
22
25
D
22
E
25
F
15
Now we have to restore the min heap property by
pushing G as far up as it can go.
G
8
8Min Priority Queue Example
A
A
10
10
B
B
G
21
21
8
C
C
D
E
F
14
14
15
22
25
D
22
Swap G with C.
E
25
F
15
G
8
9Min Priority Queue Example
A
G
10
8
B
A
B
21
10
21
C
C
D
E
F
14
14
15
22
25
D
22
Swap G with A, and we are done.
E
25
F
15
G
8
10Dijkstras Algorithm
Dijkstra(G, s) // G is a graph, s is a
source Initialize Q // Q is the min priority
queue For every vertex v in V v.Dist INF
v.Prev NULL Q.Insert(v) s.Dist 0
Q.UpdatePriority(s) For i from 0 upto V - 1
u Q.DeleteMin() // 1st iteration
removes s from Q Add u to visitation
tree VT // 1st iteration puts s into visitation
tree For every vertex u adjacent to u
and not in VT if ( u.Dist w(u, u) lt u.Dist
) u.Dist u.Dist w(u, u) u.Prev
u Q.UpdatePriority(u)
11Dijkstras Algorithm Asymptotic Analysis