B3647 【模板】Floyd
2024-10-09 本文已影响0人
louyang
使用弗洛伊德-华沙算法:
#include <iostream>
using namespace std;
#define INF 0x3f3f3f3f
int adjm[101][101], dist[101][101];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
adjm[u][v] = adjm[u][v] ? min(adjm[u][v], w) : w;
adjm[v][u] = adjm[v][u] ? min(adjm[v][u], w) : w;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
dist[i][j] = 0;
} else if (adjm[i][j]) {
dist[i][j] = adjm[i][j];
} else {
dist[i][j] = INF;
}
}
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << dist[i][j] << ' ';
}
cout << endl;
}
return 0;
}
使用贝尔曼-福特算法:
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
#define INF 0x3f3f3f3f
vector<tuple<int,int,int>> edges;
int dist[10001];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int u, v, w;
cin >> u >> v >> w;
edges.push_back({u,v,w});
edges.push_back({v,u,w});
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
dist[j] = INF;
}
dist[i] = 0;
for (int j = 1; j <= n-1; j++) {
for (auto e : edges) {
int u, v, w;
tie(u, v, w) = e;
dist[v] = min(dist[v], dist[u]+w);
}
}
for (int j = 1; j <= n; j++) {
cout << dist[j] << ' ';
}
cout << endl;
}
}