-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfloyd_warshall.cpp
More file actions
68 lines (66 loc) · 1.58 KB
/
floyd_warshall.cpp
File metadata and controls
68 lines (66 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
// Este é um algoritmo muito curto e eficiente quando
// é necessário encontrar todas as distâncias mínimas entre todos os pares/vertices.
// EXEMPLO
// 5
// 6
// 1 5 1
// 1 2 5
// 1 4 9
// 2 3 2
// 3 4 7
// 4 5 2
using namespace std;
const int INF = 1000000010;
int main()
{
int n, m;
cin >> n >> m;
int adj[n + 1][n + 1];
int distance[n + 1][n + 1];
int u, v, w;
// Criando o grafo, utilizando a matriz de adjacencia como representacao
for (int i = 0; i < m; i++)
{
cin >> u >> v >> w;
adj[u][v] = w;
adj[v][u] = w;
}
// Inicializa
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
distance[i][j] = 0;
else if (adj[i][j])
distance[i][j] = adj[i][j];
else
distance[i][j] = INF;
}
}
for (int k = 1; k <= n; k++)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]);
}
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if(i==j)
continue;
if (distance[i][j] == INF)
cout << "Não ha nenhum caminho de " << i << " para " << j << endl;
else
cout << "O caminho minimo de " << j << " para " << i << " eh " << distance[j][i] << endl;
}
cout<<endl;
}
return 0;
}