Bài giảng Toán rời rạc: Đường đi trên đồ thị (Version 0.2) cung cấp cho người học những nội dung kiến thức như: Khoảng cách và tìm kiếm theo chiều rộng, thuật toán Dijkstra, cài đặt hàng đợi ưu tiên, đường đi ngắn nhất khi có cạnh độ dài âm, đường đi ngắn nhất trong một DAG. Mời các bạn cùng tham khảo.
Trang 1Trần Vĩnh Đức
HUSTNgày 24 tháng 7 năm 2018
Trang 2Tài liệu tham khảo
▶ S Dasgupta, C H Papadimitriou, and U V Vazirani,
Algorithms, July 18, 2016.
▶ Chú ý: Nhiều hình vẽ trong tài liệu được lấy tùy tiện mà chưaxin phép
Trang 3Khoảng cách và tìm kiếm theo chiều rộng
Thuật toán Dijkstra
Cài đặt hàng đợi ưu tiên
Đường đi ngắn nhất khi có cạnh độ dài âm
Đường đi ngắn nhất trong một DAG
Trang 4DFS và đường đi
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
economical ones possible In the figure, vertex C is reachable from S by traversing
just one edge, while the DFS tree shows a path of length 3 This chapter is about
algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which differentvertices of a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph thathas a ball for each vertex and a piece of string for each edge If you lift the ball for
vertex s high enough, the other balls that get pulled up along with it are precisely the vertices reachable from s And to find their distances from s, you need only measure how far below s they hang.
In Figure 4.2, for example, vertex B is at distance 2 from S, and there are two shortest paths to it When S is held up, the strings along each of these paths become taut.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
Chapter 4
Paths in graphs
4.1 Distances
Depth-first search readily identifies all the vertices of a graph that can be reached
from a designated starting point It also finds explicit paths to these vertices,
sum-marized in its search tree (Figure 4.1) However, these paths might not be the most
economical ones possible In the figure, vertex C is reachable from S by traversing
just one edge, while the DFS tree shows a path of length 3 This chapter is about
algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which different
vertices of a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph that
has a ball for each vertex and a piece of string for each edge If you lift the ball for
vertex s high enough, the other balls that get pulled up along with it are precisely
the vertices reachable from s And to find their distances from s, you need only
measure how far below s they hang.
In Figure 4.2, for example, vertex B is at distance 2 from S, and there are two shortest
paths to it When S is held up, the strings along each of these paths become taut.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree.
Trang 5Depth-first search readily identifies all the vertices of a graph that can be reached
from a designated starting point It also finds explicit paths to these vertices,
sum-marized in its search tree (Figure 4.1) However, these paths might not be the most
economical ones possible In the figure, vertex C is reachable from S by traversing
just one edge, while the DFS tree shows a path of length 3 This chapter is about
algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which different
vertices of a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph that
has a ball for each vertex and a piece of string for each edge If you lift the ball for
vertex s high enough, the other balls that get pulled up along with it are precisely
the vertices reachable from s And to find their distances from s, you need only
measure how far below s they hang.
In Figure 4.2, for example, vertex B is at distance 2 from S, and there are two shortest
paths to it When S is held up, the strings along each of these paths become taut.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree.
B C D E
Trang 6Mô hình vật lý của đồ thị
Giả sử rằng mọi cạnh có cùng độ dài Ta nhấc đỉnh S lên:
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
BAS
On the other hand, edge (D, E ) plays no role in any shortest path and therefore
remains slack
4.2 Breadth-first search
In Figure 4.2, the lifting of s partitions the graph into layers: s itself, the nodes at
distance 1 from it, the nodes at distance 2 from it, and so on A convenient way
to compute distances from s to the other vertices is to proceed layer by layer Once
we have picked out the nodes at distance 0, 1, 2, , d, the ones at d + 1 are easily
determined: they are precisely the as-yet-unseen nodes that are adjacent to the layer
at distance d This suggests an iterative algorithm in which two layers are active at any given time: some layer d, which has been fully identified, and d + 1, which is being discovered by scanning the neighbors of layer d.
Breadth-first search (BFS) directly implements this simple reasoning (Figure 4.3)
Initially the queue Q consists only of s, the one node at distance 0 And for each subsequent distance d = 1, 2, 3, , there is a point in time at which Q contains all the nodes at distance d and nothing else As these nodes are processed (ejected
off the front of the queue), their as-yet-unseen neighbors are injected into the end
of the queue
Let’s try out this algorithm on our earlier example (Figure 4.1) to confirm that it does
the right thing If S is the starting point and the nodes are ordered alphabetically,
they get visited in the sequence shown in Figure 4.4 The breadth-first search tree,
on the right, contains the edges through which each node is initially discovered
Unlike the DFS tree we saw earlier, it has the property that all its paths from S are the shortest possible It is therefore a shortest-path tree.
Correctness and efficiency
We have developed the basic intuition behind breadth-first search In order to checkthat the algorithm works correctly, we need to make sure that it faithfully executesthis intuition What we expect, precisely, is that
For each d = 0, 1, 2, , there is a moment at which (1) all nodes at distance
≤ d from s have their distances correctly set; (2) all other nodes have their
distances set to ∞; and (3) the queue contains exactly the nodes at distance d.
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
On the other hand, edge (D, E ) plays no role in any shortest path and therefore
remains slack
4.2 Breadth-first search
In Figure 4.2, the lifting of s partitions the graph into layers: s itself, the nodes at
distance 1 from it, the nodes at distance 2 from it, and so on A convenient way
to compute distances from s to the other vertices is to proceed layer by layer Once
we have picked out the nodes at distance 0, 1, 2, , d, the ones at d + 1 are easily
determined: they are precisely the as-yet-unseen nodes that are adjacent to the layer
at distance d This suggests an iterative algorithm in which two layers are active at any given time: some layer d, which has been fully identified, and d + 1, which is
being discovered by scanning the neighbors of layer d.
Breadth-first search (BFS) directly implements this simple reasoning (Figure 4.3)
Initially the queue Q consists only of s, the one node at distance 0 And for each subsequent distance d = 1, 2, 3, , there is a point in time at which Q contains all the nodes at distance d and nothing else As these nodes are processed (ejected
off the front of the queue), their as-yet-unseen neighbors are injected into the end
of the queue
Let’s try out this algorithm on our earlier example (Figure 4.1) to confirm that it does
the right thing If S is the starting point and the nodes are ordered alphabetically,
they get visited in the sequence shown in Figure 4.4 The breadth-first search tree,
on the right, contains the edges through which each node is initially discovered
Unlike the DFS tree we saw earlier, it has the property that all its paths from S are the shortest possible It is therefore a shortest-path tree.
Correctness and efficiency
We have developed the basic intuition behind breadth-first search In order to checkthat the algorithm works correctly, we need to make sure that it faithfully executes
this intuition What we expect, precisely, is that
For each d = 0, 1, 2, , there is a moment at which (1) all nodes at distance
≤ d from s have their distances correctly set; (2) all other nodes have their
distances set to ∞; and (3) the queue contains exactly the nodes at distance d.
6 / 52 CuuDuongThanCong.com https://fb.com/tailieudientucntt
Trang 7Tìm kiếm theo chiều rộng ( B readth- F irst S earch)
On the other hand, edge (D, E ) plays no role in any shortest path and therefore
remains slack
4.2 Breadth-first search
In Figure 4.2, the lifting of s partitions the graph into layers: s itself, the nodes at
distance 1 from it, the nodes at distance 2 from it, and so on A convenient way
to compute distances from s to the other vertices is to proceed layer by layer Once
we have picked out the nodes at distance 0, 1, 2, , d, the ones at d + 1 are easily
determined: they are precisely the as-yet-unseen nodes that are adjacent to the layer
at distance d This suggests an iterative algorithm in which two layers are active at any given time: some layer d, which has been fully identified, and d + 1, which is
being discovered by scanning the neighbors of layer d.
Breadth-first search (BFS) directly implements this simple reasoning (Figure 4.3)
Initially the queue Q consists only of s, the one node at distance 0 And for each subsequent distance d = 1, 2, 3, , there is a point in time at which Q contains all the nodes at distance d and nothing else As these nodes are processed (ejected
off the front of the queue), their as-yet-unseen neighbors are injected into the end
of the queue
Let’s try out this algorithm on our earlier example (Figure 4.1) to confirm that it does
the right thing If S is the starting point and the nodes are ordered alphabetically,
they get visited in the sequence shown in Figure 4.4 The breadth-first search tree,
on the right, contains the edges through which each node is initially discovered
Unlike the DFS tree we saw earlier, it has the property that all its paths from S are the shortest possible It is therefore a shortest-path tree.
Correctness and efficiency
We have developed the basic intuition behind breadth-first search In order to checkthat the algorithm works correctly, we need to make sure that it faithfully executes
this intuition What we expect, precisely, is that
For each d = 0, 1, 2, , there is a moment at which (1) all nodes at distance
≤ d from s have their distances correctly set; (2) all other nodes have their
distances set to ∞; and (3) the queue contains exactly the nodes at distance d.
Ý tưởng thuật toán: Khi mức d đã được xác định, mức d + 1 có thể thăm bằng cách duyệt qua các hàng xóm của mức d.
7 / 52 CuuDuongThanCong.com https://fb.com/tailieudientucntt
Trang 8Ý tưởng loang theo chiều rộng
Khởi tạo: Hàng đợi Q chỉ chứa đỉnh s, là đỉnh duy nhất ở mức 0.
Với mỗi khoảng cách d = 1, 2, 3, ,
▶ sẽ có thời điểm Q chỉ chứa các đỉnh có khoảng cách d và
Trang 9Bài tập
Chạy thuật toán BFS cho đồ thị dưới đây bắt đầu từ đỉnh S Ghi
ra hàng đợi Q sau mỗi lần thăm đỉnh.
Chapter 4
Paths in graphs
4.1 Distances
Depth-first search readily identifies all the vertices of a graph that can be reached
from a designated starting point It also finds explicit paths to these vertices,
sum-marized in its search tree (Figure 4.1) However, these paths might not be the most
economical ones possible In the figure, vertex C is reachable from S by traversing
just one edge, while the DFS tree shows a path of length 3 This chapter is about
algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which different
vertices of a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph that
has a ball for each vertex and a piece of string for each edge If you lift the ball for
vertex s high enough, the other balls that get pulled up along with it are precisely
the vertices reachable from s And to find their distances from s, you need only
measure how far below s they hang.
In Figure 4.2, for example, vertex B is at distance 2 from S, and there are two shortest
paths to it When S is held up, the strings along each of these paths become taut.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree
Trang 10procedure bfs(G, s)
Input: đồ thị G = (V, E), có hướng hoặc vô hướng;
một đỉnh s ∈ V
Output: Với mỗi đỉnh u đến được từ s,
dist(u) = khoảng cách từ s tới u.
for all edges (u, v) ∈ E:
if dist(v) = ∞:
dist(v) = dist(u) + 1
Trang 11Bài tập
Hãy chạy thuật toán BFS cho đồ thị dưới đây và ghi ra nội dung
của hàng đợi Q sau mỗi bước:
Chapter 4
Paths in graphs
4.1 Distances
Depth-first search readily identifies all the vertices of a graph that can be reached
from a designated starting point It also finds explicit paths to these vertices,
sum-marized in its search tree (Figure 4.1) However, these paths might not be the most
economical ones possible In the figure, vertex C is reachable from S by traversing
just one edge, while the DFS tree shows a path of length 3 This chapter is about
algorithms for finding shortest paths in graphs.
Path lengths allow us to talk quantitatively about the extent to which different
vertices of a graph are separated from each other:
The distance between two nodes is the length of the shortest path between them.
To get a concrete feel for this notion, consider a physical realization of a graph that
has a ball for each vertex and a piece of string for each edge If you lift the ball for
vertex s high enough, the other balls that get pulled up along with it are precisely
the vertices reachable from s And to find their distances from s, you need only
measure how far below s they hang.
In Figure 4.2, for example, vertex B is at distance 2 from S, and there are two shortest
paths to it When S is held up, the strings along each of these paths become taut.
Figure 4.1 (a) A simple graph and (b) its depth-first search tree.
Trang 12Nội dung
Khoảng cách và tìm kiếm theo chiều rộng
Thuật toán Dijkstra
Cài đặt hàng đợi ưu tiên
Đường đi ngắn nhất khi có cạnh độ dài âm
Đường đi ngắn nhất trong một DAG
Trang 13Độ dài của cạnh
Chapter 4 Algorithms 107
and extremely useful properties we saw in Chapter 3 But it also means that DFS can end up taking a long and convoluted route to a vertex that is actually very close by, as in Figure 4.1 Breadth-first search makes sure to visit vertices in in- creasing order of their distance from the starting point This is a broader, shal- lower search, rather like the propagation of a wave upon water And it is achieved using almost exactly the same code as DFS—but with a queue in place of a stack.
Also notice one stylistic difference from DFS: since we are only interested in
dis-tances from s, we do not restart the search in other connected components Nodes not reachable from s are simply ignored.
4.3 Lengths on edges
Breadth-first search treats all edges as having the same length This is rarely true
in applications where shortest paths are to be found For instance, suppose you are driving from San Francisco to Las Vegas, and want to find the quickest route.
Figure 4.5 shows the major highways you might conceivably use Picking the right combination of them is a shortest-path problem in which the length of each edge (each stretch of highway) is important For the remainder of this chapter, we will
deal with this more general scenario, annotating every edge e ∈ E with a length l e.
If e = (u, v), we will sometimes also write l(u, v) or l uv.
Figure 4.5 Edge lengths often matter.
FranciscoSan
Los Angeles
Bakersfield
Sacramento
Reno
Las Vegas
409
290
95
271 133
445
291 112
275
These l e’s do not have to correspond to physical lengths They could denote time (driving time between cities) or money (cost of taking a bus), or any other quantity that we would like to conserve In fact, there are cases in which we need to use negative lengths, but we will briefly overlook this particular complication.
Trong các bài toán thực tế, mỗi cạnh e thường gắn với độ dài l e
Trang 14Câu hỏi
Liệu ta có thể sửa thuật toán BFS để nó chạy được trên đồ thị
tổng quát G = (V, E) trong đó mỗi cạnh có độ dài nguyên dương
l e?
Trang 15Tách cạnh thành các cạnh với độ dài đơn vị
4.4 Dijkstra’s algorithm
4.4.1 An adaptation of breadth-first search
Breadth-first search finds shortest paths in any graph whose edges have unit length.
Can we adapt it to a more general graph G = (V, E ) whose edge lengths l e are
positive integers?
A more convenient graph
Here is a simple trick for converting G into something BFS can handle: break G ’s
long edges into unit-length pieces by introducing “dummy” nodes Figure 4.6 shows
an example of this transformation To construct the new graph G′ ,
For any edge e = (u, v) of E , replace it by l e edges of length 1, by adding l e− 1
dummy nodes between u and v.
Graph G′ contains all the vertices V that interest us, and the distances between
them are exactly the same as in G Most importantly, the edges of G′ all have unit
length Therefore, we can compute distances in G by running BFS on G′
Figure 4.6 Breaking edges into unit-length pieces.
CA
A1
4
2 3 1
Alarm clocks
If efficiency were not an issue, we could stop here But when G has very long edges,
the G′ it engenders is thickly populated with dummy nodes, and the BFS spends
most of its time diligently computing distances to these nodes that we don’t care
about at all.
To see this more concretely, consider the graphs G and G′ of Figure 4.7, and imagine
that the BFS, started at node s of G′ , advances by one unit of distance per minute For
the first 99 minutes it tediously progresses along S − A and S − B, an endless desert
of dummy nodes Is there some way we can snooze through these boring phases
and have an alarm wake us up whenever something interesting is happening—
specifically, whenever one of the real nodes (from the original graph G ) is reached?
We do this by setting two alarms at the outset, one for node A, set to go off at
time T = 100, and one for B, at time T = 200 These are estimated times of arrival,
based upon the edges currently being traversed We doze off and awake at T = 100
to find A has been discovered At this point, the estimated time of arrival for B is
adjusted to T = 150 and we change its alarm accordingly.
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
das23402 Ch04 GTBL020-Dasgupta-v10 August 12, 2006 1:48
108 4.4 Dijkstra’s algorithm
4.4 Dijkstra’s algorithm
4.4.1 An adaptation of breadth-first search
Breadth-first search finds shortest paths in any graph whose edges have unit length.
Can we adapt it to a more general graph G = (V, E ) whose edge lengths l e are
positive integers?
A more convenient graph
Here is a simple trick for converting G into something BFS can handle: break G ’s
long edges into unit-length pieces by introducing “dummy” nodes Figure 4.6 shows
an example of this transformation To construct the new graph G′ ,
For any edge e = (u, v) of E , replace it by l e edges of length 1, by adding l e− 1
dummy nodes between u and v.
Graph G′contains all the vertices V that interest us, and the distances between
them are exactly the same as in G Most importantly, the edges of G′ all have unit
length Therefore, we can compute distances in G by running BFS on G′
Figure 4.6 Breaking edges into unit-length pieces.
CA
Alarm clocks
If efficiency were not an issue, we could stop here But when G has very long edges,
the G′ it engenders is thickly populated with dummy nodes, and the BFS spends
most of its time diligently computing distances to these nodes that we don’t care
about at all.
To see this more concretely, consider the graphs G and G′ of Figure 4.7, and imagine
that the BFS, started at node s of G′ , advances by one unit of distance per minute For
the first 99 minutes it tediously progresses along S − A and S − B, an endless desert
of dummy nodes Is there some way we can snooze through these boring phases
and have an alarm wake us up whenever something interesting is happening—
specifically, whenever one of the real nodes (from the original graph G ) is reached?
We do this by setting two alarms at the outset, one for node A, set to go off at
time T = 100, and one for B, at time T = 200 These are estimated times of arrival,
based upon the edges currently being traversed We doze off and awake at T = 100
to find A has been discovered At this point, the estimated time of arrival for B is
adjusted to T = 150 and we change its alarm accordingly.
Thay cạnh e = (u, v) bởi l e cạnh độ dài 1, bằng cách thêm l e − 1
đỉnh tạm giữa u và v.
15 / 52 CuuDuongThanCong.com https://fb.com/tailieudientucntt
Trang 16Vấn đề
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
More generally, at any given moment the breadth-first search is advancing along
certain edges of G , and there is an alarm for every endpoint node toward which it
is moving, set to go off at the estimated time of arrival at that node Some of thesemight be overestimates because BFS may later find shortcuts, as a result of future
arrivals elsewhere In the preceding example, a quicker route to B was revealed upon arrival at A However, nothing interesting can possibly happen before an alarm goes
off The sounding of the next alarm must therefore signal the arrival of the wavefront
to a real node u ∈ V by BFS At that point, BFS might also start advancing along some new edges out of u, and alarms need to be set for their endpoints.
The following “alarm clock algorithm” faithfully simulates the execution of BFS on
G′
! Set an alarm clock for node s at time 0.
! Repeat until there are no more alarms:
Say the next alarm goes off at time T, for node u Then:
– The distance from s to u is T.
– For each neighbor v of u in G :
∗ If there is no alarm yet for v, set one for time T + l(u, v).
∗ If v’s alarm is set for later than T + l(u, v), then reset it to this earlier
numeric key values (alarm times) and supports the following operations:
Insert Add a new element to the set.
Decrease-key Accommodate the decrease in key value of a particular element.1
1The name decrease-key is standard but is a little misleading: the priority queue typically does not itself
change key values What this procedure really does is to notify the queue that a certain key value has been decreased.
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
das23402 Ch04 GTBL020-Dasgupta-v10 August 12, 2006 1:48
G :
S
A
B
More generally, at any given moment the breadth-first search is advancing along
certain edges of G , and there is an alarm for every endpoint node toward which it
is moving, set to go off at the estimated time of arrival at that node Some of these might be overestimates because BFS may later find shortcuts, as a result of future
arrivals elsewhere In the preceding example, a quicker route to B was revealed upon arrival at A However, nothing interesting can possibly happen before an alarm goes
off The sounding of the next alarm must therefore signal the arrival of the wavefront
to a real node u ∈ V by BFS At that point, BFS might also start advancing along some new edges out of u, and alarms need to be set for their endpoints.
The following “alarm clock algorithm” faithfully simulates the execution of BFS on
G′
! Set an alarm clock for node s at time 0.
! Repeat until there are no more alarms:
Say the next alarm goes off at time T, for node u Then:
– The distance from s to u is T.
– For each neighbor v of u in G :
∗ If there is no alarm yet for v, set one for time T + l(u, v).
∗ If v’s alarm is set for later than T + l(u, v), then reset it to this earlier
numeric key values (alarm times) and supports the following operations:
Insert Add a new element to the set.
Decrease-key Accommodate the decrease in key value of a particular element.1
1The name decrease-key is standard but is a little misleading: the priority queue typically does not itself
change key values What this procedure really does is to notify the queue that a certain key value has been decreased.
Cả 99 bước di chuyển đầu tiên đều xử lý S − A và S − B trên các
đỉnh tạm
16 / 52 CuuDuongThanCong.com https://fb.com/tailieudientucntt
Trang 17Giải pháp: Đặt Alarm clock!
▶ Với đỉnh A, đặt hẹn T = 100
▶ Với đỉnh B, đặt hẹn T = 200
▶ Bị đánh thức khi A được thăm lúc
T = 100
▶ Ước lượng lại thời gian đến của B là
T = 150; và đặt lại Alarm cho B.
More generally, at any given moment the breadth-first search is advancing along
certain edges of G , and there is an alarm for every endpoint node toward which it
is moving, set to go off at the estimated time of arrival at that node Some of thesemight be overestimates because BFS may later find shortcuts, as a result of future
arrivals elsewhere In the preceding example, a quicker route to B was revealed upon arrival at A However, nothing interesting can possibly happen before an alarm goes
off The sounding of the next alarm must therefore signal the arrival of the wavefront
to a real node u ∈ V by BFS At that point, BFS might also start advancing along some new edges out of u, and alarms need to be set for their endpoints.
The following “alarm clock algorithm” faithfully simulates the execution of BFS on
G′
! Set an alarm clock for node s at time 0.
! Repeat until there are no more alarms:
Say the next alarm goes off at time T, for node u Then:
– The distance from s to u is T.
– For each neighbor v of u in G :
∗ If there is no alarm yet for v, set one for time T + l(u, v).
∗ If v’s alarm is set for later than T + l(u, v), then reset it to this earlier
numeric key values (alarm times) and supports the following operations:
Insert Add a new element to the set.
1The name decrease-key is standard but is a little misleading: the priority queue typically does not itself
change key values What this procedure really does is to notify the queue that a certain key value has been decreased.
17 / 52 CuuDuongThanCong.com https://fb.com/tailieudientucntt
Trang 18Thuật toán Alarm Clock
Đặt một alarm clock cho đỉnh s tại thời điểm T = 0
Lặp lại cho đến khi không còn alarm:
Giả sử alarm kêu tại thời điểm T cho đỉnh u Vậy thì:
- Khoảng cách từ s tới u là T.
- Với mỗi hàng xóm v của u trong G:
* Nếu vẫn chưa có alarm cho v, đặt alarm cho v tại thời điểm T + l(u, v).
* Nếu alarm của v đã đặt, nhưng lại muộn hơnso với
T + l(u, v),
vậy thì đặt lại alarm cho v bằng T + l(u, v).
Trang 19Ví dụ
108 4.4 Dijkstra’s algorithm
4.4 Dijkstra’s algorithm
4.4.1 An adaptation of breadth-first search
Breadth-first search finds shortest paths in any graph whose edges have unit length.
Can we adapt it to a more general graph G = (V, E ) whose edge lengths l eare
positive integers?
A more convenient graph
Here is a simple trick for converting G into something BFS can handle: break G ’s
long edges into unit-length pieces by introducing “dummy” nodes Figure 4.6 shows
an example of this transformation To construct the new graph G′ ,
For any edge e = (u, v) of E , replace it by l e edges of length 1, by adding l e− 1
dummy nodes between u and v.
Graph G′contains all the vertices V that interest us, and the distances between
them are exactly the same as in G Most importantly, the edges of G′ all have unit
length Therefore, we can compute distances in G by running BFS on G′
Figure 4.6 Breaking edges into unit-length pieces.
C A
Alarm clocks
If efficiency were not an issue, we could stop here But when G has very long edges,
the G′ it engenders is thickly populated with dummy nodes, and the BFS spends
most of its time diligently computing distances to these nodes that we don’t care
about at all.
To see this more concretely, consider the graphs G and G′ of Figure 4.7, and imagine
that the BFS, started at node s of G′ , advances by one unit of distance per minute For
the first 99 minutes it tediously progresses along S − A and S − B, an endless desert
of dummy nodes Is there some way we can snooze through these boring phases
and have an alarm wake us up whenever something interesting is happening—
specifically, whenever one of the real nodes (from the original graph G ) is reached?
We do this by setting two alarms at the outset, one for node A, set to go off at
time T = 100, and one for B, at time T = 200 These are estimated times of arrival,
based upon the edges currently being traversed We doze off and awake at T = 100
to find A has been discovered At this point, the estimated time of arrival for B is
adjusted to T = 150 and we change its alarm accordingly.
Trang 20Hàng đợi ưu tiên
Tại sao cần hàng đợi ưu tiên? Để cài đặt hệ thống Alarm
Hàng đợi ưu tiên là gì?Là một tập với mỗi phần tử được gắn vớigiá trị số (còn gọi làkhóa) và có các phép toán sau:
khóa cho trước
Khóa của mỗi phần tử (đỉnh) ở đây chính là alarm của đỉnh đó
Insert và Descrease-key để đặt alarm; Delete-min để xác địnhthời điểm alarm tiếp theo kêu
Trang 21độ dài các cạnh {l e : e ∈ E}; đỉnh s ∈ V Output: Với mỗi đỉnh u đến được từ s,
dist(u) = khoảng cách từ s tới u.
for all edges (u, v) ∈ E:
if dist(v) > dist(u) + l(u, v):
dist(v) = dist(u) + l(u, v)
decreasekey(H, v)
Trang 22Ví dụHãy chạy thuật toán Dijkstra trên đồ thị sau Sau mỗi bước, hãychỉ ra mảng prev, phần tử và khóa của hàng đợi ưu tiên.
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting
point Also shown are the associated dist values and the final shortest-path tree
A: 0 D: ∞B: 4 E: ∞C: 2
B: 3 E: 7C: 2
A: 0 D: 5B: 3 E: 6C: 2
3
B: 3 E: 6C: 2
Trang 23Ví dụ: Bước 1
Chapter 4 Algorithms 111
Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting
point Also shown are the associated dist values and the final shortest-path tree.
B
C
D
E A
4
1 3
2 4 1 3 5 2
A: 0 D: ∞ B: 4 E: ∞ C: 2
B
C
D
E A
4
2 4 1 3 5 2
B: 3 E: 7 C: 2
A: 0 D: 5 B: 3 E: 6 C: 2
B
C
D
E A
3
B: 3 E: 6 C: 2
Trang 24Ví dụ: Bước 2
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
Chapter 4 Algorithms 111
Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting
point Also shown are the associated dist values and the final shortest-path tree.
A: 0 D: ∞ B: 4 E: ∞ C: 2
B: 3 E: 7 C: 2
A: 0 D: 5 B: 3 E: 6 C: 2
B
C
D
E A
3
B: 3 E: 6 C: 2
Trang 25Ví dụ: Bước 3
Chapter 4 Algorithms 111
Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting
point Also shown are the associated dist values and the final shortest-path tree.
B
C
D
E A
4
1 3
2 4 1 3 5 2
A: 0 D: ∞ B: 4 E: ∞ C: 2
B
C
D
E A
4
2 4 1 3 5 2
B: 3 E: 7 C: 2
A: 0 D: 5 B: 3 E: 6 C: 2
B
C
D
E A
3
B: 3 E: 6 C: 2
Trang 26Ví dụ: Bước 4
P1: OSO/OVY P2: OSO/OVY QC: OSO/OVY T1: OSO
Chapter 4 Algorithms 111
Figure 4.9 A complete run of Dijkstra’s algorithm, with node A as the starting
point Also shown are the associated dist values and the final shortest-path tree.
B
C
D
E A
4
1 3
2 4 1 3 5 2
A: 0 D: ∞ B: 4 E: ∞ C: 2
B: 3 E: 7 C: 2
A: 0 D: 5 B: 3 E: 6 C: 2
B
C
D
E A
3
B: 3 E: 6 C: 2