SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
Lecture 13: All-Pairs Shortest Paths
CLRS Section 25.1
Outline of this Lecture

 

Introduction of the all-pairs shortest path problem.

 

First solution using Dijkstra’s algorithm.
Assumes no negative weight edges
  ¥   § ¥£
£ ¦£ © ¨£ ¦¤¢

¡

Needs priority queues

A (first) dynamic programming solution.
Only assumes no negative weight cycles.
First version is
  £ ¦£ ¢
 ¥

  ¥  
£ ¦£ © § £ ¦¤¢
¥£

¡

¡

Repeated squaring reduces to

No special data structures needed.
1

 
The All-Pairs Shortest Paths Problem

§ ¦¤¥ ¢
¥£

Given a weighted digraph
with weight
function
, ( is the set of real numbers),
determine the length of the shortest path (i.e., distance) between all pairs of vertices in . Here we
assume that there are no cycles with zero or negative
cost.

¡  





 ¥ © ¨

 

a
12

d

20
6 e 3
5
3
4
17

b

a
8

c

without negative cost cycle

e
4

b

−20
4

5

4
d

10

c

with negative cost cycle

2
Solution 1: Using Dijkstra’s Algorithm
If there are no negative cost edges apply Dijkstra’s algorithm to each vertex (as the source) of the digraph.

¢
§ ¤ £¡ ¢ ¢


 ©

¥£ ¡ ¤
¤
§¡ ¢ ¡

 ©


 © §


§ ¡

§ ¡

£

¡

 ©


and

§ ¡

¡¢

¡

 

¥
¦¡ ¢

£ ¦£
¥

¡

¡ ¡

¡
§ ¡

 ©


§¤ ¢ ¡¢ ¡¢

¡

time algorithm, where



Recall that D’s algorithm runs in
This gives a

.

 

If the digraph is dense, this is an

 

With more advanced (complicated) data structures
time yielding
D’s algorithm runs in
a
final algorithm. For dense
graphs this is
time.

algorithm.

§¤ ¢ ¡

3

 ©


¡¢

¡

§ § ¡¢ ¡
¤
§ §¡ ¢ ¡


 ©

¥ ¡¢

¡
Solution 2: Dynamic Programming

(1) How do we decompose the all-pairs shortest paths
problem into subproblems?

(2) How do we express the optimal solution of a
subproblem in terms of optimal solutions to some
subsubproblems?

(3) How do we use the recursive relation from (2) to
compute the optimal solution in a bottom-up
fashion?

(4) How do we construct all the shortest paths?

4
Solution 2: Input and Output Formats

¥   £ ¡
¦¡ £ ¤¤ £ ¤£ ¢ 

Assume that the graph is represented by an
matrix with the weights of the edges:
and
and


¥ # ! §  £ ¢
¥ ! §  £ ¢

 ¡ 
 ¡ 
£  ¡ 

if
if
if

¡ § ¡

¡

¥

To simplify the notation, we assume that

,
.




¨
§  £ ¢ ¨   ¡ ©¨

¡ § ¡



Output Format: an
matrix
where
is the length of the shortest path from vertex to .


¨ 



5

.



'  
(¨ %

¡ $
Step 1: How to Decompose the Original Problem

 

Subproblems with smaller sizes should be easier
to solve.

 

An optimal solution to a subproblem should be expressed in terms of the optimal solutions to subproblems with smaller sizes.

These are guidelines ONLY.

6
Step 1: Decompose in a Natural Way

¤

 

Define
to be the length of the shortest path
from to that contains at most edges.
Let
be the
matrix
.

'

¡
  
¡ £ £ ¡

¤ 



© ¨   ¨
¡¦¡  

¡ ¥

¤

¢
¦  $

¤

¢
¦  $

 

Question: Which

for

(see next

is easiest to compute?

7



¡ § ¡

Subproblems: compute



¨
£¢  § %
¥

¤

¢
¦  $
¤ 
¢   ¨
£¡

is the true distance from to
page for a proof this conclusion).
from to





 



¤ 

©
¡£ ¨ ¨ 

Proof: We prove that any shortest path
contains at most
edges.



= True Distance from to

¡  ¡

First note that since all cycles have positive weight,
a shortest path can have no cycles (if there were a
cycle, we could remove it and lower the length of the
path).

¡  ¡

A path without cycles can have length at most
(since a longer path must contain some vertex twice,
that is, contain a cycle).

8
A Recursive Formula

k

¨

¨
©§

¦

§ 
   


¡
¤¢
¢£  ¦

¡
¤¢
¥£ 

Case 2: exactly edges
shortest path

 ¨
¢  © ¦¢ ¡
¤
¡ 

¦

¡ 

¡
¤¢
¥£  ¦

¨ 
   


¡
¤¢
¢£ 

¥

Case 1: It has at most
edges.
Then
.
Case 2: It has
edges. Let be the vertex before
on a shortest path.
Then



¨



¥ ¤ 

¡

¡

¥
© £¡
¢   ¨

¤

¢   ¨
£¡

! ¨
¢  © £ !¢ ¨  ¡ £¢   ¨ 
¤
¤

Combining the two cases,

9



¥

¡
¤¢
¥£  ¦

edges

...

¡
¤¢
¢£  ¦

Case 1: at most
shortest path

i

.
¡
¤¢
¢£  ¦



j



...

¦ ¢ ¨ 

i

of length

¤

Consider a shortest path from to

j

01 ! ¨ ¢

¤ 

!
© ¦  ¨ 
¢

)

¨

! '
'% $ #(

¡

¤

¦ ¢ ¨
10



0  !

¨ ¢
, for


£ ¡ ¡ £   ¤£ £ ¡ ¥


¤ 
¤ 

!
© ¦  ¨ 
¢

¨
)

© ¦  $
¢

! '
'% $ #(

from

© ¨
¡¦  $

¤

¨  ¡

¡ 
¢¨

¡
¤

¢
¦  $

 

  $

¤ 

¦ ¢ ¨ 

 

Compute
using

, the weight matrix.

¤ 

Bottom:

Step 3: Bottom-up Computation of
¤ 

© £  $
¨

Example: Bottom-up Computation of
Example
3
8

1

2
11

4

4
3

4

7

is just the weight matrix:
¨
©§
¨

 ¡



¨


¡ ¡
¦


11

¨
' ©¨ %

¡
¤
¥



¡



£






¥

¢

¡

¤ 

  $

¡

¤ 

  $
12


¦


£

¡ ¡
¥

¡
¥

¦



¦

¡

¨
¨

¨
©§

£

¥

¡ ¡
 
¡¡

¢

¡ ¥  $
¤

¡
¡
 ¡

given earlier and the recursive formula,
3
4

11
2

¨ ¢

0
1 !


  $

from

¤ 

¤ 

  $

With

7

4
4
3
8

¤ 

¥  $
¤

!
  ¨ 
)

1

 $ ! #(
%' '

¡ ¥   ¨ 
¤

Example: Computing
0

¤ §

  $

)

¤

!  ¨
 ! ¨ ¢ ¥ ¡
2
11

4

¡

 % ' $ ! #(
'

¤ §

  ¨
¡

4
3

4

7

given earlier and the recursive formula,
¨
©§
¨

¡

¨
¥



¡ ¡
¦



 ¡

¤

¥  $

With

¥  $

3
8

1

from

¤

Example: Computing

¡
¦

£
¥

¡ ¡

 ¡
¦

¥

 
¡¡

¡ ¡
¥

¢

¡

¡

¤ §

  $

gives the distances between any pair of vertices.

13

¤ §

  $
14

;

¡ ¥ ¡
¤

¨ §¡
¨ ¤ ¡ ¡ ¡ ¥ ¡ ¥
¤
! ¨
¢!  ¨
¢  © £¡ ¡ ¨ ¤ ¡
¤
)

¡

¢   ¨
£¡
¢

¢

if (

;

;

;
to

¡

¡

¡

 

¡

to

¡

for

¡ ¡ ¥



¡

¡ 

¡  ¡

¡

 

for

to

© ¨
¡¦  $

¡

¡ 

for

to

¤ 

¡ ¥

for

The Algorithm for Computing
Comments on Solution 2

¢
 ¡§ ¥ ¡
§ § ¡¢

¡

space; how can this be

¡

 

Algorithm uses
reduced down to

 

How can we extract the actual shortest paths from
the solution?

§  ¡¢

Running time
, much worse than the solution using Dijkstra’s algorithm. Can we improve
this?

15

¢

 
Repeated Squaring

¤ 

Observe that we are only interested to find
, all
others
are only auxiliary. Furthermore, since the graph does not have negative cycle,
, for all
.
we have

© £  $
¨

¨ $

¡
¡ ¢

¤ 



©¡£  $ ¡
¨
 © £
¨§¦¥¤¥ ¢ $

using “repeated squar

©
¨§!¥£ ¥ ¢ $ £

¡

¤ 

© ¨
¡¦  $



 ©
  §¦¥£ ¥ ¢ $

 ¤


We can calculate
ing” to find



     ¡
£¨ $

£  ¡

In particular, this implies that

16

 
 
 
£¤ $£¤ $ £¤¥ $
We use the recurrence relation:

, the weight matrix.

¤

! '
!¨
 ¡
% ' $ #¢
¡
¤
)
 
¡
¢¥ $

using

¤   £


¥ $

¤

¡

0  ¡
 !

¢

  $

compute



¨  ¡


¨
¡

¨

¡

¤

¡
¢¥

 
 

For

¤ 

Bottom:

¡

¡
 

  ¨
¡

¤
¥ £

¥ $

Given this relation we can calculate
from
in
time. We can therefore calculate all of

¤



¢

¨
£ 
$ ¡
 ©
  §¦¥£ ¥ $ £

 
¤ ¤£

¤



§ § ¡¢

§ ¡  © § ¡ ¢

  $
 
 
£¤ $ £¤¥ $
¢

¢

in

time, improving our running time.

17
The Floyd-Warshall Algorithm
Step 1 : Decomposition

©
¥
§
¨¡¦ 
¡
 
£  ¦  £   ¤£   £  ¥¤ © ¡ ¡ £

 ¢  £   ¤£ §   £ ¥  


Definition: The vertices
intermediate vertices of the path

are called the

¤ !

 

Let
be the length of the shortest path from
to such that all intermediate vertices on the path
(if any) are in set
.



£

¡
£ ¤£ ¢ 
£

 
¤¤

, i.e., no intermediate vertex.
.

'   ¨  %

matrix

¤ !

¡ § ¡
¨
©¨

is the distance from to . So our aim



for

¡

¤ !

  $

¤

¨
£  $

¨   ¨
£¡

  $

©   ¨
¡

Subproblems: compute

¡ £ £ ¡ £
 

.

18





¤

¤ !

¤

 

is to compute





Claim:

be the

¥

  ¨
¡

Let

is set to be

.

 
Step 2: Structure of shortest paths
Observation 1: A shortest path does not contain the
same vertex twice.
Proof: A path containing the
same vertex twice contains a cycle. Removing cycle
gives a shorter path.
Observation 2: For a shortest path from to such
that any intermediate vertices on the path are chosen
, there are two possibilities:
from the set





¥

.

¤ 

!

©   ¨ 

!
©   ¡
¢  © !  ! ¨ 
¤
!

 
¤¤

¡
£ ¤£ ¢ 
£

2. is a vertex on the path.
The shortest such path has length

¤ 

£

1. is not a vertex on the path,
The shortest such path has length

19

.
Step 2: Structure of shortest paths
Consider a shortest path from to containing the
vertex . It consists of a subpath from to and a
subpath from to .
Each subpath can only contain intermediate vertices
, and must be as short as possible,
in
namely they have lengths
and
.





¤ 

¤ 





¤ 

!

©   ! 

!

¥ ¡ 

!
©   ¨ 

©   ! 
¢  © !  ! ¨ 
¤
!

¡
£    £ ¢ 

Hence the path has length

.

Combining the two cases we get

20

0

¤ 

!

©   !  ¢

¤ 

!

¨
©   ¨ 
£¤  © !  
!

)

%$ #

¤ !

¡   ¨
21

.
¡

¤ 

©  ¡
 !
!

 ¨
 ¨
¢  © ! !¡ £  © ! ¡
¤
¤
©   $
¤ 

!

¡ £ £ ¡ ¡
¡ ¡
 ¨

%
$ #
 

¤ !

from


' ¨ ¨ %

¡

  $

¤ !

 

 

Compute

¤

for

Bottom:

using

, the weight matrix.

©
  $

Step 3: the Bottom-up Computation
22

'
¡
©  
' 
£  % ¤  !  ¡ ¡ ' 
'
£
¢ ' £ %  © !    ¡ '  £
'  ¤ ©  
£ %¤ !  ¢ ' £
;

;

©  
' 
£ %  ! 
'  ¤ %   
 £ ¤ !
¡

¢

¨
¦ 
¡
£ ¡    ¡ % ¤ 
£ % !  
 %  ¤ ¤ ££
% !   
% ¤ ©   
¤  ¡! ¡¢ 

¢

return

else

;

 

for
to do
for
to do
for
to do
if

;

dynamic programming

¡

¡

¡

¡

¡

¡ 

¡


¡ '  £  %  ¤ ¡£
 
¢ ¡
'  % ¨ ¡ '  % © $
£
£
¡ 

¢

;

;

¡

¡

 

Floyd-Warshall(
)
for
to do
for
to do

initialize

¡ 

¡

¡

¡£ ¨

 

The Floyd-Warshall Algorithm: Version 1
Comments on the Floyd-Warshall Algorithm

§ § ¡¢
¡

 

The algorithm’s running time is clearly

 

The predecessor pointer
can be used
to extract the final path (see later ).

 

Problem: the algorithm uses
space.
It is possible to reduce this down to
space
by keeping only one matrix instead of .
Algorithm is on next page. Convince yourself that
it works.

.

'

¡
§ ¥ ¡¢

23

©
£

§ ¥ £ ¡
¨% ¦¤¢ 

¡
§ § ¡¢

¡
24

;

¢

;

¡

;

¡
' 
£ %  ¢ ' £ % 
§ '  £ %  '  £

¡% 
' ¡ ¡
 £ ¡
 
'   %  ¤ ££
¡£' 
£ % 
%  ¢ ' %  ¢
£
¡ 

¢

return

 

for
to do
for
to do
for
to do
if

dynamic programming

;
;

¡

¡

¡

¡

¡

¡

¡ 

¡


¡ '  £  %  ¤ ¡£
 
¢ ¡
'  % ¨ ¡ '  % 
£
¡

¡

¡£ 

¢

 

Floyd-Warshall(
)
for
to do
for
to do

initialize

¡

¡

¡£ ¨

¡ 

 

The Floyd-Warshall Algorithm: Version 2
Extracting the Shortest Paths

©
£

The predecessor pointers
can be used to
extract the final path. The idea is as follows.

'

§ % ¦£ ¢ 
¥ ¡

Whenever we discover that the shortest path from
to passes through an intermediate vertex , we set
.





¡ '  £  %  ¤ ¡£
 

If the shortest path does not pass through any inter.
mediate vertex, then

¡ '
 
£  %  ¤ ££


¢ ¡


§  £ ¢
 
'   %  ¤ ££
£

To find the shortest path from to , we consult
.
If it is nil, then the shortest path is just the edge
.
Otherwise, we recursively compute the shortest path
and the shortest path from
from to
to .

 
'   %  ¤ ¡£
£
25





 
'   %  ¤ ¡£
£
The Algorithm for Extracting the Shortest Paths
)

 

§  ¡ £ ' ¢ 
 
£  %  ¤ ¡£

if (


¢ ¡


£

Path(

)

single edge

output
;
compute the two parts of the path
else
 


 
£ '  £  %    ¤ ££
' 
£  %  ¤ ¡£ £ 

Path(
Path(

);
);

¢
¢

26
27
£

¡ ¡
£  £ ¢  ¢ ¢  ¡
¡ ¡
£  £ ¢  ¢ ¢  ¡
¤
£¡
¢  ¢ ¢  ¡
£
¡
¢  ¢ ¢  ¡
 

£

£

¡
¡
¡

¤
 
' ¦%  ¤ ¡£
' ¤£ %   
¤ ¡£
 
' £ %  ¤ ¡£
' £  %   
¤ ¡£
 
'   £ %  ¤ ¡£
' £ £%   
¤ ¡£
 
' £ £
£ £ %  ¤ ¡£

(4,6)
(6,3)
(2,5)
(5,4)

¥
¥

¥

¡

¥

¡

¡£ 
¡
£ 

¡
¥

£

¡

£

¤
§ £ ¥¢
§ ¤£ ¢
§ £ ¢
§ £  ¢
§  £ £¢
§ £ £¢
§ £ £¢
¥

£

¥

¥

¥

£

Path
Path
Path
Path
Path
Path
Path

£

¤

¥
¥

¤

£
 ¥
¤
 £ ¥
£
 ¥
£
 ¥  
 
 £ ¥
 £

 

  £
  £
  £
  £

£
£



£


£



Find the shortest path from vertex 2 to vertex 3.
Example of Extracting the Shortest Paths

Más contenido relacionado

Similar a All pairts shortest path class 18

Predim. vigas sabado
Predim. vigas   sabadoPredim. vigas   sabado
Predim. vigas sabado
patrick_amb
 
Exposicion 1_Diseño de canales mediante abacos.pptx
Exposicion 1_Diseño de canales mediante abacos.pptxExposicion 1_Diseño de canales mediante abacos.pptx
Exposicion 1_Diseño de canales mediante abacos.pptx
JosueOrtiz80
 
Introducción al Calculo de Varias Variables MA-III ccesa007
Introducción al Calculo de Varias Variables  MA-III  ccesa007Introducción al Calculo de Varias Variables  MA-III  ccesa007
Introducción al Calculo de Varias Variables MA-III ccesa007
Demetrio Ccesa Rayme
 

Similar a All pairts shortest path class 18 (18)

Algortimo Cartero Chino.
Algortimo Cartero Chino.Algortimo Cartero Chino.
Algortimo Cartero Chino.
 
Mecanica de-materiales-ii ricardo cortez olivera
Mecanica de-materiales-ii ricardo cortez oliveraMecanica de-materiales-ii ricardo cortez olivera
Mecanica de-materiales-ii ricardo cortez olivera
 
F4002 - L05 - Solución de ecuaciones diferenciales ordinarias (problemas de v...
F4002 - L05 - Solución de ecuaciones diferenciales ordinarias (problemas de v...F4002 - L05 - Solución de ecuaciones diferenciales ordinarias (problemas de v...
F4002 - L05 - Solución de ecuaciones diferenciales ordinarias (problemas de v...
 
Slides costo anisotropico
Slides costo anisotropicoSlides costo anisotropico
Slides costo anisotropico
 
Ayudantia N°8.pptx
Ayudantia N°8.pptxAyudantia N°8.pptx
Ayudantia N°8.pptx
 
Juntas universales
Juntas universalesJuntas universales
Juntas universales
 
Tema 1.6 determinacion de los parametros cto equiv.
Tema 1.6  determinacion de los parametros cto equiv. Tema 1.6  determinacion de los parametros cto equiv.
Tema 1.6 determinacion de los parametros cto equiv.
 
Predim. vigas sabado
Predim. vigas   sabadoPredim. vigas   sabado
Predim. vigas sabado
 
01 curvas en rn
01 curvas en rn01 curvas en rn
01 curvas en rn
 
Exposicion 1_Diseño de canales mediante abacos.pptx
Exposicion 1_Diseño de canales mediante abacos.pptxExposicion 1_Diseño de canales mediante abacos.pptx
Exposicion 1_Diseño de canales mediante abacos.pptx
 
Introducción al Calculo de Varias Variables MA-III ccesa007
Introducción al Calculo de Varias Variables  MA-III  ccesa007Introducción al Calculo de Varias Variables  MA-III  ccesa007
Introducción al Calculo de Varias Variables MA-III ccesa007
 
Calculo de Varias Variables ccesa007
Calculo de Varias Variables  ccesa007Calculo de Varias Variables  ccesa007
Calculo de Varias Variables ccesa007
 
Ecuaciones de Maxwell y ondas electromagnéticas.pdf
Ecuaciones de Maxwell y ondas electromagnéticas.pdfEcuaciones de Maxwell y ondas electromagnéticas.pdf
Ecuaciones de Maxwell y ondas electromagnéticas.pdf
 
Fuentes del campo magnético.docx
Fuentes del campo magnético.docxFuentes del campo magnético.docx
Fuentes del campo magnético.docx
 
ejercicios_4_stevenson.pdf
ejercicios_4_stevenson.pdfejercicios_4_stevenson.pdf
ejercicios_4_stevenson.pdf
 
Vectores y tensores para fenómenos de transporte
Vectores y tensores para fenómenos de transporteVectores y tensores para fenómenos de transporte
Vectores y tensores para fenómenos de transporte
 
Porfolio estrecho
Porfolio estrechoPorfolio estrecho
Porfolio estrecho
 
Mapeo de Potencial Eléctrico
Mapeo de Potencial EléctricoMapeo de Potencial Eléctrico
Mapeo de Potencial Eléctrico
 

Más de Kumar

Más de Kumar (20)

Graphics devices
Graphics devicesGraphics devices
Graphics devices
 
Fill area algorithms
Fill area algorithmsFill area algorithms
Fill area algorithms
 
region-filling
region-fillingregion-filling
region-filling
 
Bresenham derivation
Bresenham derivationBresenham derivation
Bresenham derivation
 
Bresenham circles and polygons derication
Bresenham circles and polygons dericationBresenham circles and polygons derication
Bresenham circles and polygons derication
 
Introductionto xslt
Introductionto xsltIntroductionto xslt
Introductionto xslt
 
Extracting data from xml
Extracting data from xmlExtracting data from xml
Extracting data from xml
 
Xml basics
Xml basicsXml basics
Xml basics
 
XML Schema
XML SchemaXML Schema
XML Schema
 
Publishing xml
Publishing xmlPublishing xml
Publishing xml
 
DTD
DTDDTD
DTD
 
Applying xml
Applying xmlApplying xml
Applying xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
How to deploy a j2ee application
How to deploy a j2ee applicationHow to deploy a j2ee application
How to deploy a j2ee application
 
JNDI, JMS, JPA, XML
JNDI, JMS, JPA, XMLJNDI, JMS, JPA, XML
JNDI, JMS, JPA, XML
 
EJB Fundmentals
EJB FundmentalsEJB Fundmentals
EJB Fundmentals
 
JSP and struts programming
JSP and struts programmingJSP and struts programming
JSP and struts programming
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 
Introduction to J2EE
Introduction to J2EEIntroduction to J2EE
Introduction to J2EE
 

Último

Criterios ESG: fundamentos, aplicaciones y beneficios
Criterios ESG: fundamentos, aplicaciones y beneficiosCriterios ESG: fundamentos, aplicaciones y beneficios
Criterios ESG: fundamentos, aplicaciones y beneficios
JonathanCovena1
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Francisco158360
 

Último (20)

proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niñoproyecto de mayo inicial 5 añitos aprender es bueno para tu niño
proyecto de mayo inicial 5 añitos aprender es bueno para tu niño
 
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
LABERINTOS DE DISCIPLINAS DEL PENTATLÓN OLÍMPICO MODERNO. Por JAVIER SOLIS NO...
 
Criterios ESG: fundamentos, aplicaciones y beneficios
Criterios ESG: fundamentos, aplicaciones y beneficiosCriterios ESG: fundamentos, aplicaciones y beneficios
Criterios ESG: fundamentos, aplicaciones y beneficios
 
PIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonablesPIAR v 015. 2024 Plan Individual de ajustes razonables
PIAR v 015. 2024 Plan Individual de ajustes razonables
 
MAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grandeMAYO 1 PROYECTO día de la madre el amor más grande
MAYO 1 PROYECTO día de la madre el amor más grande
 
Estrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcciónEstrategia de prompts, primeras ideas para su construcción
Estrategia de prompts, primeras ideas para su construcción
 
La triple Naturaleza del Hombre estudio.
La triple Naturaleza del Hombre estudio.La triple Naturaleza del Hombre estudio.
La triple Naturaleza del Hombre estudio.
 
Sesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docxSesión de aprendizaje Planifica Textos argumentativo.docx
Sesión de aprendizaje Planifica Textos argumentativo.docx
 
Presentacion Metodología de Enseñanza Multigrado
Presentacion Metodología de Enseñanza MultigradoPresentacion Metodología de Enseñanza Multigrado
Presentacion Metodología de Enseñanza Multigrado
 
plan de capacitacion docente AIP 2024 clllll.pdf
plan de capacitacion docente  AIP 2024          clllll.pdfplan de capacitacion docente  AIP 2024          clllll.pdf
plan de capacitacion docente AIP 2024 clllll.pdf
 
Qué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativaQué es la Inteligencia artificial generativa
Qué es la Inteligencia artificial generativa
 
Registro Auxiliar - Primaria 2024 (1).pptx
Registro Auxiliar - Primaria  2024 (1).pptxRegistro Auxiliar - Primaria  2024 (1).pptx
Registro Auxiliar - Primaria 2024 (1).pptx
 
actividades comprensión lectora para 3° grado
actividades comprensión lectora para 3° gradoactividades comprensión lectora para 3° grado
actividades comprensión lectora para 3° grado
 
origen y desarrollo del ensayo literario
origen y desarrollo del ensayo literarioorigen y desarrollo del ensayo literario
origen y desarrollo del ensayo literario
 
Programacion Anual Matemática4 MPG 2024 Ccesa007.pdf
Programacion Anual Matemática4    MPG 2024  Ccesa007.pdfProgramacion Anual Matemática4    MPG 2024  Ccesa007.pdf
Programacion Anual Matemática4 MPG 2024 Ccesa007.pdf
 
Valoración Crítica de EEEM Feco2023 FFUCV
Valoración Crítica de EEEM Feco2023 FFUCVValoración Crítica de EEEM Feco2023 FFUCV
Valoración Crítica de EEEM Feco2023 FFUCV
 
Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...Caja de herramientas de inteligencia artificial para la academia y la investi...
Caja de herramientas de inteligencia artificial para la academia y la investi...
 
Plan Refuerzo Escolar 2024 para estudiantes con necesidades de Aprendizaje en...
Plan Refuerzo Escolar 2024 para estudiantes con necesidades de Aprendizaje en...Plan Refuerzo Escolar 2024 para estudiantes con necesidades de Aprendizaje en...
Plan Refuerzo Escolar 2024 para estudiantes con necesidades de Aprendizaje en...
 
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdfCurso = Metodos Tecnicas y Modelos de Enseñanza.pdf
Curso = Metodos Tecnicas y Modelos de Enseñanza.pdf
 
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICABIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
BIOMETANO SÍ, PERO NO ASÍ. LA NUEVA BURBUJA ENERGÉTICA
 

All pairts shortest path class 18

  • 1. Lecture 13: All-Pairs Shortest Paths CLRS Section 25.1 Outline of this Lecture   Introduction of the all-pairs shortest path problem.   First solution using Dijkstra’s algorithm. Assumes no negative weight edges ¥ § ¥£ £ ¦£ © ¨£ ¦¤¢ ¡ Needs priority queues A (first) dynamic programming solution. Only assumes no negative weight cycles. First version is £ ¦£ ¢ ¥ ¥ £ ¦£ © § £ ¦¤¢ ¥£ ¡ ¡ Repeated squaring reduces to No special data structures needed. 1  
  • 2. The All-Pairs Shortest Paths Problem § ¦¤¥ ¢ ¥£ Given a weighted digraph with weight function , ( is the set of real numbers), determine the length of the shortest path (i.e., distance) between all pairs of vertices in . Here we assume that there are no cycles with zero or negative cost. ¡   ¥ © ¨   a 12 d 20 6 e 3 5 3 4 17 b a 8 c without negative cost cycle e 4 b −20 4 5 4 d 10 c with negative cost cycle 2
  • 3. Solution 1: Using Dijkstra’s Algorithm If there are no negative cost edges apply Dijkstra’s algorithm to each vertex (as the source) of the digraph. ¢ § ¤ £¡ ¢ ¢ © ¥£ ¡ ¤ ¤ §¡ ¢ ¡ © © § § ¡ § ¡ £ ¡ © and § ¡ ¡¢ ¡   ¥ ¦¡ ¢ £ ¦£ ¥ ¡ ¡ ¡ ¡ § ¡ © §¤ ¢ ¡¢ ¡¢ ¡ time algorithm, where Recall that D’s algorithm runs in This gives a .   If the digraph is dense, this is an   With more advanced (complicated) data structures time yielding D’s algorithm runs in a final algorithm. For dense graphs this is time. algorithm. §¤ ¢ ¡ 3 © ¡¢ ¡ § § ¡¢ ¡ ¤ § §¡ ¢ ¡ © ¥ ¡¢ ¡
  • 4. Solution 2: Dynamic Programming (1) How do we decompose the all-pairs shortest paths problem into subproblems? (2) How do we express the optimal solution of a subproblem in terms of optimal solutions to some subsubproblems? (3) How do we use the recursive relation from (2) to compute the optimal solution in a bottom-up fashion? (4) How do we construct all the shortest paths? 4
  • 5. Solution 2: Input and Output Formats ¥ £ ¡ ¦¡ £ ¤¤ £ ¤£ ¢  Assume that the graph is represented by an matrix with the weights of the edges: and and ¥ # ! § £ ¢ ¥ ! § £ ¢ ¡ ¡ £ ¡ if if if ¡ § ¡ ¡ ¥ To simplify the notation, we assume that , . ¨ § £ ¢ ¨ ¡ ©¨ ¡ § ¡ Output Format: an matrix where is the length of the shortest path from vertex to . ¨ 5 . ' (¨ % ¡ $
  • 6. Step 1: How to Decompose the Original Problem   Subproblems with smaller sizes should be easier to solve.   An optimal solution to a subproblem should be expressed in terms of the optimal solutions to subproblems with smaller sizes. These are guidelines ONLY. 6
  • 7. Step 1: Decompose in a Natural Way ¤   Define to be the length of the shortest path from to that contains at most edges. Let be the matrix . ' ¡ ¡ £ £ ¡ ¤ © ¨  ¨ ¡¦¡   ¡ ¥ ¤ ¢ ¦  $ ¤ ¢ ¦  $   Question: Which for (see next is easiest to compute? 7 ¡ § ¡ Subproblems: compute ¨ £¢  § % ¥ ¤ ¢ ¦  $ ¤ ¢  ¨ £¡ is the true distance from to page for a proof this conclusion).
  • 8. from to   ¤ © ¡£ ¨ ¨ Proof: We prove that any shortest path contains at most edges. = True Distance from to ¡ ¡ First note that since all cycles have positive weight, a shortest path can have no cycles (if there were a cycle, we could remove it and lower the length of the path). ¡ ¡ A path without cycles can have length at most (since a longer path must contain some vertex twice, that is, contain a cycle). 8
  • 9. A Recursive Formula k ¨ ¨ ©§ ¦ § ¡ ¤¢ ¢£  ¦ ¡ ¤¢ ¥£  Case 2: exactly edges shortest path  ¨ ¢ © ¦¢ ¡ ¤ ¡ ¦ ¡ ¡ ¤¢ ¥£  ¦ ¨ ¡ ¤¢ ¢£  ¥ Case 1: It has at most edges. Then . Case 2: It has edges. Let be the vertex before on a shortest path. Then ¨ ¥ ¤ ¡ ¡ ¥ © £¡ ¢  ¨ ¤ ¢  ¨ £¡ ! ¨ ¢ © £ !¢ ¨ ¡ £¢   ¨ ¤ ¤ Combining the two cases, 9 ¥ ¡ ¤¢ ¥£  ¦ edges ... ¡ ¤¢ ¢£  ¦ Case 1: at most shortest path i . ¡ ¤¢ ¢£  ¦ j ... ¦ ¢ ¨ i of length ¤ Consider a shortest path from to j 01 ! ¨ ¢ ¤ ! © ¦  ¨ ¢ ) ¨ ! ' '% $ #( ¡ ¤ ¦ ¢ ¨
  • 10. 10 0 ! ¨ ¢ , for £ ¡ ¡ £ ¤£ £ ¡ ¥ ¤ ¤ ! © ¦  ¨ ¢ ¨ ) © ¦  $ ¢ ! ' '% $ #( from © ¨ ¡¦  $ ¤ ¨  ¡ ¡ ¢¨ ¡ ¤ ¢ ¦  $     $ ¤ ¦ ¢ ¨   Compute using , the weight matrix. ¤ Bottom: Step 3: Bottom-up Computation of
  • 11. ¤ © £  $ ¨ Example: Bottom-up Computation of Example 3 8 1 2 11 4 4 3 4 7 is just the weight matrix: ¨ ©§ ¨  ¡ ¨ ¡ ¡ ¦ 11 ¨ ' ©¨ % ¡ ¤ ¥ ¡ £ ¥ ¢ ¡ ¤   $ ¡ ¤   $
  • 12. 12 ¦ £ ¡ ¡ ¥ ¡ ¥ ¦ ¦ ¡ ¨ ¨ ¨ ©§ £ ¥ ¡ ¡   ¡¡ ¢ ¡ ¥  $ ¤ ¡ ¡  ¡ given earlier and the recursive formula, 3 4 11 2 ¨ ¢ 0 1 !   $ from ¤ ¤   $ With 7 4 4 3 8 ¤ ¥  $ ¤ !   ¨ ) 1 $ ! #( %' ' ¡ ¥   ¨ ¤ Example: Computing
  • 13. 0 ¤ §   $ ) ¤ !  ¨ ! ¨ ¢ ¥ ¡ 2 11 4 ¡ % ' $ ! #( ' ¤ §  ¨ ¡ 4 3 4 7 given earlier and the recursive formula, ¨ ©§ ¨ ¡ ¨ ¥ ¡ ¡ ¦  ¡ ¤ ¥  $ With ¥  $ 3 8 1 from ¤ Example: Computing ¡ ¦ £ ¥ ¡ ¡ ¡ ¦ ¥   ¡¡ ¡ ¡ ¥ ¢ ¡ ¡ ¤ §   $ gives the distances between any pair of vertices. 13 ¤ §   $
  • 14. 14 ; ¡ ¥ ¡ ¤ ¨ §¡ ¨ ¤ ¡ ¡ ¡ ¥ ¡ ¥ ¤ ! ¨ ¢!  ¨ ¢ © £¡ ¡ ¨ ¤ ¡ ¤ ) ¡ ¢  ¨ £¡ ¢ ¢ if ( ; ; ; to ¡ ¡ ¡   ¡ to ¡ for ¡ ¡ ¥ ¡ ¡ ¡ ¡ ¡   for to © ¨ ¡¦  $ ¡ ¡ for to ¤ ¡ ¥ for The Algorithm for Computing
  • 15. Comments on Solution 2 ¢  ¡§ ¥ ¡ § § ¡¢ ¡ space; how can this be ¡   Algorithm uses reduced down to   How can we extract the actual shortest paths from the solution? § ¡¢ Running time , much worse than the solution using Dijkstra’s algorithm. Can we improve this? 15 ¢  
  • 16. Repeated Squaring ¤ Observe that we are only interested to find , all others are only auxiliary. Furthermore, since the graph does not have negative cycle, , for all . we have © £  $ ¨ ¨ $ ¡ ¡ ¢ ¤ ©¡£  $ ¡ ¨ © £ ¨§¦¥¤¥ ¢ $ using “repeated squar © ¨§!¥£ ¥ ¢ $ £ ¡ ¤ © ¨ ¡¦  $ © §¦¥£ ¥ ¢ $ ¤ We can calculate ing” to find     ¡ £¨ $ £ ¡ In particular, this implies that 16       £¤ $£¤ $ £¤¥ $
  • 17. We use the recurrence relation: , the weight matrix. ¤ ! ' !¨  ¡ % ' $ #¢ ¡ ¤ )   ¡ ¢¥ $ using ¤ £ ¥ $ ¤ ¡ 0 ¡  ! ¢   $ compute ¨  ¡ ¨ ¡ ¨ ¡ ¤ ¡ ¢¥     For ¤ Bottom: ¡ ¡    ¨ ¡ ¤ ¥ £ ¥ $ Given this relation we can calculate from in time. We can therefore calculate all of ¤ ¢ ¨ £  $ ¡ © §¦¥£ ¥ $ £ ¤ ¤£ ¤ § § ¡¢ § ¡ © § ¡ ¢   $     £¤ $ £¤¥ $ ¢ ¢ in time, improving our running time. 17
  • 18. The Floyd-Warshall Algorithm Step 1 : Decomposition © ¥ § ¨¡¦  ¡   £ ¦  £ ¤£   £ ¥¤ © ¡ ¡ £ ¢  £ ¤£ §   £ ¥   Definition: The vertices intermediate vertices of the path are called the ¤ !   Let be the length of the shortest path from to such that all intermediate vertices on the path (if any) are in set . £ ¡ £ ¤£ ¢  £ ¤¤ , i.e., no intermediate vertex. . '   ¨ % matrix ¤ ! ¡ § ¡ ¨ ©¨ is the distance from to . So our aim for ¡ ¤ !   $ ¤ ¨ £  $ ¨  ¨ £¡   $ ©  ¨ ¡ Subproblems: compute ¡ £ £ ¡ £ . 18 ¤ ¤ ! ¤   is to compute Claim: be the ¥  ¨ ¡ Let is set to be .  
  • 19. Step 2: Structure of shortest paths Observation 1: A shortest path does not contain the same vertex twice. Proof: A path containing the same vertex twice contains a cycle. Removing cycle gives a shorter path. Observation 2: For a shortest path from to such that any intermediate vertices on the path are chosen , there are two possibilities: from the set ¥ . ¤ ! ©   ¨ ! ©  ¡ ¢ © !  ! ¨ ¤ ! ¤¤ ¡ £ ¤£ ¢  £ 2. is a vertex on the path. The shortest such path has length ¤ £ 1. is not a vertex on the path, The shortest such path has length 19 .
  • 20. Step 2: Structure of shortest paths Consider a shortest path from to containing the vertex . It consists of a subpath from to and a subpath from to . Each subpath can only contain intermediate vertices , and must be as short as possible, in namely they have lengths and . ¤ ¤ ¤ ! ©  ! ! ¥ ¡ ! ©   ¨ ©  ! ¢ © !  ! ¨ ¤ ! ¡ £ £ ¢  Hence the path has length . Combining the two cases we get 20 0 ¤ ! ©  ! ¢ ¤ ! ¨ ©   ¨ £¤ © !  ! ) %$ # ¤ ! ¡   ¨
  • 21. 21 . ¡ ¤ © ¡  ! !  ¨  ¨ ¢ © ! !¡ £ © ! ¡ ¤ ¤ ©   $ ¤ ! ¡ £ £ ¡ ¡ ¡ ¡  ¨ % $ #   ¤ ! from ' ¨ ¨ % ¡   $ ¤ !     Compute ¤ for Bottom: using , the weight matrix. ©   $ Step 3: the Bottom-up Computation
  • 22. 22 ' ¡ ©   ' £ % ¤ ! ¡ ¡ ' ' £ ¢ ' £ % © !   ¡ ' £ ' ¤ ©   £ %¤ ! ¢ ' £ ; ; ©   ' £ % ! ' ¤ %   £ ¤ ! ¡ ¢ ¨ ¦  ¡ £ ¡   ¡ % ¤ £ % !  % ¤ ¤ ££ % !   % ¤ ©   ¤ ¡! ¡¢ ¢ return else ;   for to do for to do for to do if ; dynamic programming ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ' £ % ¤ ¡£   ¢ ¡ ' % ¨ ¡ ' % © $ £ £ ¡ ¢ ; ; ¡ ¡   Floyd-Warshall( ) for to do for to do initialize ¡ ¡ ¡ ¡£ ¨   The Floyd-Warshall Algorithm: Version 1
  • 23. Comments on the Floyd-Warshall Algorithm § § ¡¢ ¡   The algorithm’s running time is clearly   The predecessor pointer can be used to extract the final path (see later ).   Problem: the algorithm uses space. It is possible to reduce this down to space by keeping only one matrix instead of . Algorithm is on next page. Convince yourself that it works. . ' ¡ § ¥ ¡¢ 23 © £ § ¥ £ ¡ ¨% ¦¤¢  ¡ § § ¡¢ ¡
  • 24. 24 ; ¢ ; ¡ ; ¡ ' £ % ¢ ' £ % § ' £ % ' £ ¡% ' ¡ ¡ £ ¡   ' % ¤ ££ ¡£' £ % % ¢ ' % ¢ £ ¡ ¢ return   for to do for to do for to do if dynamic programming ; ; ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ¡ ' £ % ¤ ¡£   ¢ ¡ ' % ¨ ¡ ' % £ ¡ ¡ ¡£ ¢   Floyd-Warshall( ) for to do for to do initialize ¡ ¡ ¡£ ¨ ¡   The Floyd-Warshall Algorithm: Version 2
  • 25. Extracting the Shortest Paths © £ The predecessor pointers can be used to extract the final path. The idea is as follows. ' § % ¦£ ¢  ¥ ¡ Whenever we discover that the shortest path from to passes through an intermediate vertex , we set . ¡ ' £ % ¤ ¡£   If the shortest path does not pass through any inter. mediate vertex, then ¡ '   £ % ¤ ££ ¢ ¡ § £ ¢   ' % ¤ ££ £ To find the shortest path from to , we consult . If it is nil, then the shortest path is just the edge . Otherwise, we recursively compute the shortest path and the shortest path from from to to .   ' % ¤ ¡£ £ 25   ' % ¤ ¡£ £
  • 26. The Algorithm for Extracting the Shortest Paths )   § ¡ £ ' ¢   £ % ¤ ¡£ if ( ¢ ¡ £ Path( ) single edge output ; compute the two parts of the path else     £ ' £ %   ¤ ££ ' £ % ¤ ¡£ £ Path( Path( ); ); ¢ ¢ 26
  • 27. 27 £ ¡ ¡ £  £ ¢  ¢ ¢ ¡ ¡ ¡ £  £ ¢  ¢ ¢ ¡ ¤ £¡ ¢  ¢ ¢ ¡ £ ¡ ¢  ¢ ¢ ¡   £ £ ¡ ¡ ¡ ¤   ' ¦% ¤ ¡£ ' ¤£ %   ¤ ¡£   ' £ % ¤ ¡£ ' £  %   ¤ ¡£   '   £ % ¤ ¡£ ' £ £%   ¤ ¡£   ' £ £ £ £ % ¤ ¡£ (4,6) (6,3) (2,5) (5,4) ¥ ¥ ¥ ¡ ¥ ¡ ¡£  ¡ £  ¡ ¥ £ ¡ £ ¤ § £ ¥¢ § ¤£ ¢ § £ ¢ § £  ¢ §  £ £¢ § £ £¢ § £ £¢ ¥ £ ¥ ¥ ¥ £ Path Path Path Path Path Path Path £ ¤ ¥ ¥ ¤ £ ¥ ¤ £ ¥ £ ¥ £ ¥   £ ¥ £     £   £   £   £ £ £ £ £ Find the shortest path from vertex 2 to vertex 3. Example of Extracting the Shortest Paths