Projeto e Análise de Algoritmos - Aula 13 - Problema do caminho mais curto

UNIVESP
2 Oct 201722:43

Summary

TLDRThis video script discusses the shortest path problem in graphs, specifically focusing on the Dijkstra's algorithm for finding the shortest path from a single origin to all other vertices. It explains the concept of relaxation, the importance of non-negative weights for correct results, and how the algorithm constructs a shortest path tree from the origin. The script also touches on the Bellman-Ford algorithm, which handles negative weights and detects negative cycles, and provides an example to illustrate the algorithm's process.

Takeaways

  • 📚 The lecture introduces the problem of finding the shortest path in a graph with a single origin.
  • 🛣️ The problem is modeled using a graph where vertices represent cities and edges represent paths between cities, each with a weight.
  • 🔢 The weight of an edge could represent the distance or cost to travel, calculated as the sum of the prices of all edges in a path.
  • 📈 The shortest path is determined by calculating the weights of all possible paths and finding the minimum.
  • 🔄 An important characteristic of shortest paths is the optimal substructure, where any subpath of the shortest path is also the shortest path between its endpoints.
  • ⚠️ Negative weight cycles can cause issues in shortest path calculations, as they can lead to infinitely decreasing path weights.
  • 🛠️ Two well-known algorithms for solving the single-source shortest path problem are Dijkstra's algorithm and the Bellman-Ford algorithm.
  • 🚀 Dijkstra's algorithm assumes all edge weights are non-negative and is efficient for graphs without negative weight cycles.
  • 🔄 The Bellman-Ford algorithm can handle graphs with negative weight edges but is more generic and may have a higher processing time.
  • 🌳 The result of the shortest path problem is a shortest-path tree rooted at the source vertex, showing the shortest path to all reachable vertices.
  • 🔄 The relaxation step in algorithms is crucial for updating the estimated shortest path weights and determining the parent vertices in the shortest-path tree.

Q & A

  • What is the main topic of the video script?

    -The main topic of the video script is the shortest path problem in graphs, focusing on algorithms for finding the shortest path from a single source to all other vertices.

  • What is the problem modeled in the script?

    -The problem modeled in the script is finding the shortest path from Rio de Janeiro to São Paulo, represented as a graph where cities are vertices and the distances between them are edges with weights.

  • What is the weight of an edge in the context of the script?

    -In the context of the script, the weight of an edge represents the distance or cost of the path between two cities.

  • What is the formula used to calculate the total weight of a path?

    -The total weight of a path is calculated as the sum of the weights of all the edges that make up the path.

  • What is the property of shortest paths that is referred to as the 'greedy property'?

    -The 'greedy property' refers to the characteristic that if you have the shortest path from the source to a vertex, any subpath of that path is also the shortest path between the start and end vertices of the subpath.

  • What happens when there are negative weights in the graph?

    -When there are negative weights in the graph, it can lead to a situation where the shortest path cannot be determined if there is a cycle with negative total weight, as passing through the cycle an infinite number of times would result in a path with a weight approaching negative infinity.

  • What are the two well-known algorithms mentioned in the script for solving the single-source shortest path problem?

    -The two well-known algorithms mentioned in the script are Dijkstra's algorithm and Bellman-Ford algorithm.

  • How does Dijkstra's algorithm handle negative weights?

    -Dijkstra's algorithm does not handle negative weights well because it assumes all edge weights are non-negative. It does not account for the possibility of negative cycles that could lead to infinite paths.

  • What is the data structure used by the Bellman-Ford algorithm to keep track of the shortest paths?

    -The Bellman-Ford algorithm uses two sets: one for vertices whose shortest path distance is definitive (known) and one for vertices whose distance is still an estimate (provisional).

  • What is the result of running the shortest path algorithms in the script?

    -The result of running the shortest path algorithms is a shortest path tree rooted at the source vertex, which shows the shortest path to all other reachable vertices.

  • How does the Bellman-Ford algorithm perform the relaxation step?

    -The Bellman-Ford algorithm performs the relaxation step by checking if the current estimate of the shortest path to a vertex can be improved by going through another vertex. If an improvement is found, it updates the estimate and the parent of the vertex in question.

Outlines

00:00

🛣️ Introduction to Shortest Path Problem

This paragraph introduces the concept of the shortest path problem in graph theory, specifically focusing on the single-source shortest path from Rio de Janeiro to São Paulo. It explains how to model the problem using a graph where vertices represent cities and edges represent the paths between them, each with a weight representing distance. The paragraph also discusses the importance of non-negative weights for the optimal substructure property and introduces the notion of a relaxation technique used in algorithms to find the shortest path.

05:01

🔄 Negative Cycles and Algorithms for Shortest Paths

The second paragraph delves into the complications that arise when negative weight cycles exist in a graph, which can lead to an undefined shortest path. It contrasts two well-known algorithms for shortest path problems: Dijkstra's algorithm, which assumes all edge weights are non-negative, and Bellman-Ford algorithm, which can handle negative weights but detects negative cycles. The paragraph explains that the Bellman-Ford algorithm constructs a shortest path tree rooted at the source, showing the shortest paths to all reachable vertices.

10:02

🔄 Relaxation Step in Shortest Path Algorithms

This paragraph explains the relaxation step used in shortest path algorithms, which involves checking if a shorter path to a vertex can be found by passing through another vertex. It illustrates how to update the estimated shortest path if a better path is discovered. The explanation includes an example with a graph of five vertices, showing how to initialize the algorithm and perform relaxation to improve the path estimates, ultimately finding the shortest paths from the source vertex to all other vertices.

15:03

📈 The Bellman-Ford Algorithm's Relaxation Process

The fourth paragraph provides a detailed walkthrough of the Bellman-Ford algorithm's relaxation process. It describes the initialization of estimates and the iterative process of updating these estimates by considering each vertex and its adjacent edges. The paragraph uses a step-by-step example to demonstrate how the algorithm refines the shortest path estimates for each vertex until it converges on the definitive shortest paths from the source to all other reachable vertices.

20:04

🌳 Completion of the Shortest Path Tree

The final paragraph concludes the explanation of the Bellman-Ford algorithm by detailing the completion of the shortest path tree. It shows how the algorithm determines the definitive shortest path to each vertex and updates the tree accordingly. The paragraph ends with a summary of the algorithm's process and an example of the final shortest path tree, highlighting the minimum distances and the edges that constitute the shortest paths from the source vertex.

Mindmap

Keywords

💡Graph

A graph is a mathematical structure consisting of a set of vertices (or nodes) and a set of edges that connect pairs of vertices. In the context of the video, a graph is used to model a network of cities where vertices represent cities and edges represent the paths between them. The script uses graphs to explain how to find the shortest path between cities, such as from Rio de Janeiro to São Paulo.

💡Shortest Path

The shortest path in graph theory is the path with the minimum sum of edge weights between two vertices. The video discusses algorithms to find this path, emphasizing its importance in routing and navigation, such as finding the shortest route from one city to another.

💡Relaxation

Relaxation in the context of the video refers to a technique used in pathfinding algorithms where the algorithm iteratively improves the estimate of the shortest path to a vertex. The script describes this process as updating the path cost when a cheaper path is found, which is central to the functioning of the Dijkstra's algorithm.

💡Dijkstra's Algorithm

Dijkstra's Algorithm is a pathfinding algorithm that calculates the shortest paths from a single source vertex to all other vertices in a graph with non-negative edge weights. The video explains how this algorithm works, starting with an initial estimate of infinity for all paths and then iteratively improving these estimates through the relaxation process.

💡Vertex

A vertex, also known as a node, is a fundamental unit of a graph, representing an entity such as a city in the video's example. Vertices are connected by edges, and the script discusses how algorithms determine the shortest path from one vertex to another.

💡Edge

An edge in a graph connects two vertices, representing a path or connection between them. The video mentions edges as having weights, such as distances between cities, which are crucial for calculating the shortest path.

💡Weight

In the context of graphs, a weight is a numerical value associated with an edge, indicating the cost or distance of traversing that edge. The video script discusses how weights are used in algorithms to determine the shortest path, with the sum of weights along a path being minimized.

💡Negative Cycle

A negative cycle in a graph is a cycle where the total sum of the edge weights is negative. The script warns that the presence of a negative cycle can make the shortest path undefined, as traversing the cycle an infinite number of times would result in a path with a cost less than any finite value.

💡BFS (Breadth-First Search)

Although not explicitly named in the script, the concept of breadth-first search is implied when discussing how algorithms explore all possible paths from the source vertex. BFS is an algorithm for traversing or searching tree or graph data structures, which the video contrasts with Dijkstra's algorithm that accounts for edge weights.

💡Priority Queue

A priority queue is an abstract data type in which each element has a priority, and the order in which elements are processed is determined by their priorities. The video script mentions the use of a priority queue in Dijkstra's algorithm to efficiently select the next vertex to relax.

💡Estimate

In the context of the video, an estimate refers to the current best guess of the shortest path to a vertex. The script describes how these estimates are initially set to infinity and then improved upon as the algorithm progresses through the relaxation steps.

Highlights

Introduction to the shortest path problem in graphs with a single source.

Explanation of the relaxation technique used in shortest path algorithms.

Discussion on modeling real-world problems like finding the shortest route from Rio de Janeiro to São Paulo as graph problems.

Definition of vertices and edges in the context of graph theory and their relation to cities and paths.

Explanation of how edge weights represent distances between cities in the graph model.

Introduction to the concept of path weight as the sum of the weights of all edges in the path.

Description of the all-pairs shortest path problem and the method to find the shortest path between all pairs of vertices.

Explanation of the optimal substructure property of shortest paths.

Discussion on the implications of negative weight edges and their impact on shortest path calculations.

Introduction to the Bellman-Ford algorithm and its ability to handle graphs with negative weight edges.

Explanation of the Dijkstra's algorithm and its limitations regarding negative weight edges.

Presentation of the algorithm's result as a shortest path tree rooted at the source vertex.

Description of the initialization step in the Dijkstra's algorithm where all distances are set to infinity except the source.

Explanation of the relaxation step in Dijkstra's algorithm where the shortest path estimates are updated.

Introduction to the use of priority queues in the Dijkstra's algorithm to efficiently select the next vertex to relax.

Discussion on the time complexity and practical applications of the Dijkstra's algorithm.

Overview of the algorithm's implementation and its steps using a visual example with a graph.

Conclusion of the lecture with a summary of the Dijkstra's algorithm and its significance in solving real-world shortest path problems.

Transcripts

play00:00

[Música]

play00:07

o

play00:07

[Música]

play00:14

olá pessoal sejam bem vindos à nossa

play00:17

aula número 13 do projeto em análise

play00:19

algoritmos nessa hora vemos o problema

play00:22

de caminho mais curto de uma única

play00:25

origem grafos

play00:27

vamos ver a técnica de relaxamento e

play00:31

vamos ver apenas um algoritmo que faz

play00:34

essa tarefa que o algoritmo de destro

play00:37

suponha que você deseja encontrar o

play00:40

caminho mais curto possível

play00:42

desde o rio de janeiro até são paulo

play00:47

então entra aqui para aqui como é

play00:51

terminar rota mais curta

play00:53

nesse caso a gente pode modelar esse

play00:56

problema como um problema em gráficos

play00:59

você vai ter um grafo conversa encerrar

play01:02

esta em que os vértices são as cidades e

play01:05

as áreas são os caminhos entre essas

play01:07

cidades se você vai ter um peso nessas

play01:10

tarefas então cada aresta vai ter um

play01:12

peso associado que seria por exemplo

play01:14

nesse caso a distância entre o peso de

play01:20

um caminhão como que vai ser calculado

play01:22

então dá um caminhão p

play01:24

aqui temos um caminho que vai de vencer

play01:27

o avaí eo e terminei ver k vai ser

play01:31

calculado como a soma dos preços de

play01:33

todas as arestas que passam por esses

play01:35

sete meses que seria essa fórmula 1

play01:38

daqui então temos que o peso no caminho

play01:42

p essa uma história dos preços das

play01:46

arestas que vão de 90 cm não sou um

play01:49

atleta e sair com lhe dizer um até cá

play01:53

como definimos então o peso do caminho

play01:56

mais curto de seu a tv de maneira

play01:59

genérica a gente vai calcular os preços

play02:02

de todos os caminhos possíveis

play02:06

isso porque assim existe um caminho ou a

play02:09

tv

play02:10

pegamos todos os caminhos possíveis e o

play02:12

atv e calculamos com o que vai ser o

play02:15

mínimo então isso vai ser em tom é

play02:18

definiu como o caminho mais curto desvio

play02:22

antes eo atleta

play02:25

então não existe um caminho de uma tv

play02:29

essa distância deu à tv mais sedada mas

play02:32

só definirá como infinito tem uma

play02:39

característica importante nos caminhos

play02:43

mais curtos que a subir estrutura ótima

play02:45

está definido aqui nesses lá e depois

play02:48

vamos ver um exemplo do que significa

play02:50

isso seja um grafo g que tem um conjunto

play02:53

levanta e se um conjunto de erez da

play02:56

sombra foi orientado e compensamos isso

play02:58

querem ser ponderado e seja um caminho

play03:02

neste gráfico vamos supor que temos um

play03:04

caminho que segui todos esses vetos e vê

play03:08

uma tv cá

play03:10

se a gente pega um sub caminho desse

play03:13

caminho vamos supor que pegamos uma

play03:15

parte desse sucesso desse caminho que

play03:18

seria por exemplo esse caminho pj que

play03:20

vai desde 96 atletas e j

play03:24

esses subica minho também vai ser o

play03:28

caminho mais curto dizia a tj se esse

play03:32

caminho daqui era o caminho mais curto

play03:35

deveu à tv cá de maneira sempre vamos

play03:39

ver aqui então é sempre um sobre isso

play03:42

suponha que você conhece qualquer uma o

play03:45

menor caminho do rio de janeiro até são

play03:50

paulo

play03:51

se você já tem isso isso porque esse

play03:54

realmente o melhor caminho do rio de

play03:57

janeiro em são paulo

play03:58

se a gente pega o sub caminho desse

play04:02

caminho esse caminho também vai ser um

play04:05

caminho mais curto entre essas cidades

play04:07

por exemplo se a gente pega o caminho

play04:09

desde agora tem que tá até são paulo

play04:14

esse caminho aqui esse caminho aqui

play04:18

também vai ser um sub caminho mais curto

play04:21

entre a cidade e agora tem tá até são

play04:25

paulo

play04:28

uma outra característica que precisamos

play04:30

é ver investigar e que acontece quando

play04:34

temos áreas de pressão negativa

play04:37

o carro pode vir a lista de peso

play04:39

negativo sim claro no nosso exemplo

play04:42

anterior que sobre a distância sobre

play04:45

caminhos entre as cidades a distância

play04:47

não pode ser negativo mas para outros 60

play04:49

anos poderia ter-se uma distância

play04:52

negativa 1 um peso negativo na verdade

play04:55

nas áreas como nem sempre a descer grafo

play04:57

que temos aqui em baixo os pesos do

play05:01

caminho de caminhos mais curtos não vão

play05:03

estar bem definidos caso assista um

play05:06

ciclo de peso negativo

play05:08

como nesse exemplo de quim aqui temos um

play05:11

ciclo de peso negativo e seria esse de

play05:14

quinta e se a p&g ps cujo valor seria

play05:20

menos dois

play05:21

toda vez que a gente passa por esse

play05:23

ciclo a gente vai ter menos 2 - 2 - 2 -

play05:26

2 - 2 - 2 se a gente passa infinitamente

play05:29

por ele vai ser menos infinito

play05:32

é então que aconteça com isso a gente

play05:35

não pôde calcular qual que o caminho

play05:37

mais curto quando a gente tem ciclos de

play05:40

peso negativo se um ciclo de peso

play05:47

negativo em algum grafo num caminho de

play05:50

se a tv

play05:51

então vamos definir que a distância

play05:54

desse a tv - infinito

play05:59

existem dois organismos conhecidos para

play06:02

resolver o problema de caminho mais

play06:04

curto de um homem de origem que são o

play06:07

algoritmo de dastan e orgulho de ver na

play06:09

foto o algoritmo de desta ele vai supor

play06:13

que todos os presos as arestas um grafo

play06:15

são negativos

play06:17

então com ele por exemplo podemos

play06:19

resolver o problema do caminho mais

play06:21

curto de são paulo até qualquer outra

play06:24

cidade do brasil por exemplo né e

play06:28

organismo verma for ele permitem arestas

play06:32

e pessoal negativo no gráfico sim o que

play06:35

ele vai fazer

play06:36

na verdade ele vai verificar se esses em

play06:38

ciclos e caso esses ciclos ele vai

play06:41

detectar isso e vai produzir uma

play06:44

resposta correta para o problema

play06:49

o resultado da busca do caminho mais

play06:53

curto é uma árvore ray sada no na origem

play06:57

então ele vai mostrar qual é o caminho

play06:59

mais curto desde a origem em ciência a

play07:02

tecnologia verde e acessível a partir

play07:04

desse quem mais a gente já tinha falhado

play07:06

isso antes também quando a gente

play07:08

trabalhava com algoritmos de busca em

play07:10

profundidade em buscas na largura

play07:12

na verdade o algoritmo de busca em

play07:16

largura em gráficos

play07:18

porém nesse caso a gente não trabalhava

play07:21

com os pesos entre é nessas áreas não

play07:23

tínhamos peso nas arestas

play07:26

nesse caso temos é temos um caso do mapa

play07:30

uma distância entre uma cidade e outra

play07:33

por exemplo

play07:34

então o resultado do do caminho mais

play07:38

curto resolver o problema o caminho mais

play07:40

curto vai ser uma árvore

play07:41

aqui temos um exemplo de um grafo e aqui

play07:44

temos um exemplo das duas possíveis

play07:47

árvores que poderia ser a solução do

play07:50

caminho mais curto para esse grafo estão

play07:52

mostrando se aqui então temos aqui

play07:58

essa árvore que está enraizada em s

play08:02

e ele está mostrando que o caminho mais

play08:04

curto para ir de se ater e passar

play08:07

exatamente porém saretta de si até que o

play08:10

custo e 3 o caminho mais curto para ir

play08:14

dance

play08:15

a tx tem um pessoal de 9 e ela passa

play08:19

pelo vértice ele passa pela está e ct-e

play08:24

área tx e assim por diante

play08:27

temos uma outra opção que também tem os

play08:29

mesmos valores

play08:30

é um caminho mais curto também mas que

play08:33

passa por outras arestas

play08:35

quem sabe aqui um caminho mais curto de

play08:40

si até 3 o caminho mais curto de se a y

play08:44

r 5

play08:46

mas ela passa pela área está e citei

play08:49

pela está tem destino certo que os

play08:54

custos são iguais então são duas

play08:56

possíveis soluções para o mesmo problema

play08:58

o estado orismar de weimar for quanto o

play09:02

agora os modais

play09:03

para ele usa eles usam a técnica de

play09:05

relaxamento

play09:07

eles vão ter que calcular uma estimativa

play09:09

do mapa do caminho mais curto que vão

play09:12

chamar de de dever

play09:14

então em de ver a gente vai aguardar o

play09:17

limite superior sobre o peso do caminho

play09:20

mais curto desde a origem ea tevê início

play09:23

quando não sabemos nada um grafo esse

play09:26

limite superior vai ser infinito não sei

play09:28

qualquer chance de dizer se a teoria é

play09:31

que se qualquer

play09:32

então vou colocar infinito então

play09:34

primeiro vamos fazer a inicialização

play09:36

passou de inicialização que eu acabei de

play09:38

falar

play09:39

como não sabemos nada a estimativa de

play09:43

qualquer e é o valor do caminho mais

play09:46

curto até cada vez e ver mas ser

play09:49

infinito não sabemos quem são os pais

play09:51

não só colocar mil e sabemos que a

play09:54

instância de origem e se a teoria inss

play09:58

serão a gente já está no próprio vértice

play10:02

agora então vamos ver o passo de

play10:05

relaxamento

play10:06

esse passo de relaxamento consiste em

play10:09

verificar se podemos melhorar o caminho

play10:12

mais curto para ver encontrado até agora

play10:15

pela passagem através de u

play10:17

se acontecer isso vamos atualizar a

play10:21

nossa estimativa de e também que o pai é

play10:25

então como key é feito isso se a gente

play10:29

tem uma estimativa a tba tv de s

play10:33

isso porque a gente tem é se a gente tem

play10:36

aqui a gente tem uma estimativa de

play10:40

qualquer instância passado por outros

play10:42

vezes até 90 cv

play10:44

isso porque ela é de dever e agora a

play10:48

gente vai verificar se passado por uma

play10:52

agente consiga melhorar isso não tá

play10:54

agora vamos ter a estimativa até u

play11:01

vamos ver se um samba a esta o v

play11:05

a gente consiga melhorar essa estimativa

play11:08

vamos supor que eu sei que o dever de 20

play11:15

eu sei

play11:17

que o dedé eo é tri é vou colocar um

play11:20

número menor de 15 e à distância entre

play11:25

um e vem e 3 seu olho aqui então passado

play11:30

por um eu posso melhorar a minha

play11:32

estimativa a tv

play11:34

agora vai ser 18 no lugar de 20

play11:37

isso é o que está sendo feito aqui se a

play11:40

estimativa que eu tinha a tv é maior que

play11:44

a estimativa que eu tenho até o mais o

play11:47

pessoal da arysta o v

play11:50

então eu posso melhorar a minha

play11:53

estimativa como esse valor e aí a

play11:55

polícia que em que o pai de ver o pai de

play11:59

ver eu seja a gente está atualizando

play12:02

quem que o pai de ver agora passava pelo

play12:06

para chegar em ver esse é o processo de

play12:10

relaxamento

play12:11

então quem quer faz valores mobiliários

play12:15

da extra ele vai calcular qual é o

play12:17

caminho mais curto tem uma única origem

play12:18

em um algoritmo orgulhoso

play12:21

nesse caso ele só permite que as arestas

play12:24

tenha peso positivo em consequentemente

play12:28

não vai ter ciclos de peso negativo ele

play12:30

não vai precisar se preocupar com isso

play12:34

além disso o tempo de execução o curso

play12:38

de processamento dele é inferior ao

play12:40

coritiba for que um pouquinho mais

play12:42

genérico que ele pode se trabalhar com

play12:45

arestas negativas valores modais

play12:49

trabalha com dois conjuntos evets o

play12:51

conjunto esse que são os doentes cuja

play12:53

distância para arraes shea conhecida é

play12:57

ou seja é a definitiva e um conjunto

play13:00

vermelho não sei se é que o conjunto de

play13:02

veto e sem que a distância é conhecida

play13:05

ainda é uma estimativa provisória seja

play13:07

apenas em estimativa não sei se é

play13:09

exatamente isso não

play13:10

para isso o algoritmo vai utilizar duas

play13:14

estruturas

play13:16

o ec que vai ser um conjunto de eventos

play13:18

cuja distância é definitiva e o que para

play13:22

para guardar os 76 quando estância

play13:25

provisória é esse que vai ser uma filha

play13:29

de prioridade

play13:30

mínima e aqui temos então o pessoal do

play13:33

código do algoritmo de da strans

play13:35

ele usa o algoritmo que faz a

play13:39

inicialização das estimativas e o

play13:43

relaxamento das estimativas aqui para

play13:46

ver o funcionamento desse terrorismo

play13:50

vou mostrar aqui um exemplo então

play13:51

suponho que temos um grafo com cinco

play13:54

vértice o vertis e é ct x e y en sei que

play13:59

estão aqui também nessa tabela em baixo

play14:02

e temos a qualquer o peso de cada uma

play14:06

das areias neste gráfico também queremos

play14:09

saber qual é o caminho mais curto desse

play14:12

ato até todos os verdes e atingíveis a

play14:14

partir desse aqui nessa tabela vamos

play14:17

guardando qualquer estimativa que são os

play14:22

pais que vai ter a fila de prioridades e

play14:26

o que vai ter um conjunto esse certo

play14:29

então no início o primeiro que vai ser

play14:32

feito vai ser a um passo de

play14:34

inicialização no momento inicializar a

play14:38

gente vai colocar que a nossa estimativa

play14:41

é infinito para todo mundo

play14:44

os pais é exceto para o noé se que a

play14:48

instância dsts e terceiro quem são os

play14:52

pais todo mundo uniu a gente não sabe

play14:54

quem é o pai na área da resposta

play14:57

e aí depois a gente vai ver é

play15:02

inicializar o conjunto e se com vazio e

play15:05

o conjunto que com todos os répteis que

play15:07

está aqui mostrado com 11 chega e aí

play15:14

depois enquanto a filha não esteja vazia

play15:17

o que vai ser feito

play15:19

continuamos aqui enquanto a filha não

play15:21

seja macia a não ser o mínimo do

play15:25

conjunto que o mínimo do conjunto que

play15:29

nesse caso é aquele que tem a estimativa

play15:33

melhor nesse caso o fcs

play15:36

vamos colocar em tom e se esse evento

play15:40

disse

play15:41

vamos colocar no conjunto esse maiúscula

play15:44

esse aqui

play15:45

ok o próximo passo é então fazer um

play15:50

relaxamento das arestas

play15:52

o que vamos nos perguntar nesse passo

play15:54

será que podemos melhorar o caminho mais

play15:55

curto

play15:56

att que são um dos grandes ideais de

play15:59

acidentes a esse é encontrado até agora

play16:02

pela passagem através desse sim a gente

play16:06

tem estava infinita a nossa estimativa

play16:08

passando por esse a gente tem um caminho

play16:12

mais curto que o tamanho 10 certo

play16:16

faremos o mesmo com o outro vértice que

play16:19

a gente sente a ele que o y e aí

play16:23

perguntava será que podemos melhorar o

play16:25

caminho mais curto até este não

play16:27

encontraram até agora pela passagem

play16:29

desse sim

play16:30

a minha estimativa é infinito e agora eu

play16:33

tenho uma estimativa de 5 passando por

play16:36

pelo ipc s

play16:39

então vamos atualizar esses valores aqui

play16:43

então temos agora que os valores foram

play16:46

atualizados para 5 e 10 aqui também

play16:49

vamos atualizar nossa tabela a nossa

play16:51

estimativa mudou e agora o próximo passo

play16:58

é original ou extrair um mínimo da da

play17:01

filha que tem o valor mínimo da fila na

play17:04

filha eu tenho te x y e c que tem um

play17:08

valor mínimo é o y então vou extrair o y

play17:11

e vou colocar ele no conjunto e se estou

play17:14

colocando aqui no conjunto e se depois

play17:17

vamos passar de novo passo de

play17:18

relaxamento no passo do relaxamento a

play17:21

gente vai verificar todos os dentes

play17:23

adjacentes à distância definitiva mínima

play17:27

até o efeito senão já sabemos que cinco

play17:31

que agora vamos ver os recentes certo

play17:34

então será que podemos melhorar o

play17:35

caminho mais curto para quem são os

play17:37

agentes então os recentes vão ctx ec x e

play17:44

certo será que podemos melhorar o

play17:47

caminho mais curto para ter encontrado

play17:50

até agora pela passagem através da y

play17:54

então vamos lá se passamos

play17:57

por aqui será que podemos melhorar a

play18:00

instância a att sim se a gente passa por

play18:06

esse caminho aqui vamos a ter uma

play18:08

distância menor que vai ser oito

play18:11

o mesmo perguntamos para x será que

play18:13

podemos melhorar o caminho mais curto

play18:14

para a x encontrado até agora pela

play18:16

passagem através de y se a gente vai por

play18:20

aqui vamos ter uma distância de 5 mais

play18:24

93 se que o mesmo será que podemos

play18:27

melhorar o caminho mais curto atc sim

play18:31

a minha estimativa é infinito

play18:34

se passamos por isso não vou ter cinco

play18:36

mais 271 então vamos atualizar todos

play18:39

esses valores na tabela

play18:41

então vou ter a minha estimativa att

play18:44

mudou que em 2008 a tx mudou que 14 e

play18:47

até segunda o q7 e assim continuamos e

play18:51

agora vamos perguntar quem é o menor

play18:54

elemento que está na nossa filha ok é

play18:58

que termine estância menor estimativa

play19:01

menor é um vai acontecer

play19:04

colocámos em tom e vai acontecer no

play19:07

conjunto é esse

play19:08

ok e agora temos a distância definitiva

play19:12

a gente já sabe que a distância mínima

play19:14

até o fcc e 7 e aí continuamos com os

play19:19

vizinhos ele para ver se podemos

play19:21

melhorar o caminho mais curto

play19:23

e aí nós perguntamos será que podemos

play19:25

melhorar o caminho mais curto para a x

play19:28

encontrado até agora pela passagem

play19:30

através de z

play19:32

então estamos aqui a gente está aqui ea

play19:35

gente tenta usar tenta chegar em x

play19:38

usando esse areia aqui será que o valor

play19:41

melhorar a estimativa do x fica melhor

play19:45

então temos sim passamos por aqui 17 + 6

play19:48

3 6 3 e melhor de 14 é então vamos mudar

play19:51

o valor dele foi mudado para 3 se o

play19:57

próximo passo vamos tirar o elemento que

play20:00

o elemento menor com esse motivo o menor

play20:03

da fila que o vento e ct colocamos ele

play20:06

no conjunto e se verificamos

play20:10

já sabemos a verdade é que ela está a

play20:12

ser definitivo a mínima até 2078

play20:15

verificamos sujacente sair perguntando

play20:17

será que podemos melhorar o caminho mais

play20:19

curto para x encontrado até agora pela

play20:24

passagem através de t

play20:26

então se a gente olha aqui se os amuos

play20:29

pensar esta é que é a chegar em x será

play20:33

que a estimativa fica melhor fica

play20:35

vai ficar 8 mais 19 e aqui há a

play20:37

exigência não se machuca era 3 então

play20:40

melhorarmos a nossa estimativa o que

play20:42

agora é 9 finalmente o o o vértice único

play20:48

vai dizer que está na fila eu x quem

play20:51

ontem vizinhos não têm mais nada então

play20:54

já sabemos que a estância definitivo a

play20:56

miníma de 96 x 109 e então por fim

play21:01

acabamos com esse evento e já sabemos

play21:05

coloquei-a a nossa árvore está a mostrar

play21:09

aqui então a a nossa água e responsa em

play21:13

saber que já sabemos quais são as

play21:18

distâncias mínimas de cada vez e na

play21:20

verdade a partir do fcs até todos os 86

play21:24

atingíveis a partir desse a distância

play21:27

mínima de 100 a y e cinco de distância

play21:30

mínima de si até e 8 dez efe a x-9 dse c

play21:35

e 7 c e as arestas pelas quais temos que

play21:40

passar para as para chegar nesse nosso

play21:43

está marcado aí na árvore no vermelho

play21:46

bom essa foi a nossa aula número 3 se

play21:49

sobre o algoritmo de da estrada

play21:52

principalmente espero que vocês tenham

play21:54

gostado

play21:56

[Música]

play22:16

[Música]

play22:25

[Música]

play22:33

[Música]

Rate This

5.0 / 5 (0 votes)

相关标签
Dijkstra's AlgorithmShortest PathGraph TheoryEducational TutorialPathfindingAlgorithm AnalysisData StructuresComputer ScienceOptimizationRoute Planning
您是否需要英文摘要?