-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloyd_Warshall.cpp
More file actions
56 lines (48 loc) · 1.33 KB
/
Floyd_Warshall.cpp
File metadata and controls
56 lines (48 loc) · 1.33 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
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
// Find All Shortest Path, O(n^3)
// Graph may have negative weight but no have negative weight cycle
// if graph have negative weight cycle, exist a vertex v such that dist[v][v] < 0
constexpr int64_t INF = 1e18;
vector dist(n, vector<int64_t>(n, INF));
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
u--, v--;
dist[u][v] = min<int64_t>(dist[u][v], w);
dist[v][u] = min<int64_t>(dist[v][u], w);
}
for (int i = 0; i < n; i++) {
dist[i][i] = 0;
}
auto floyd_warshall = [&]() -> void {
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][k] < INF && dist[k][j] < INF) {
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
}
};
floyd_warshall();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << dist[i][j] << " \n"[j == n - 1];
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}