- 用来算多源间最短距离和路径。
- 时间复杂度 O(n^3)
- 空间复杂度 O(n^2)
- 稠密图效果最佳,边权可正可负
#include <bits/stdc++.h>
typedef long long LL;
const int MAXN = 100;
const int INF = 0x3f3f3f3f;
using namespace std;
int path[MAXN + 3][MAXN + 3], dist[MAXN + 3][MAXN + 3]; //path 储存路径; dist 存储最短距离
void floyd(int n, int dist[][MAXN + 3]) {
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) dist[i][j] = dist[i][j], path[i][j] = j; //初始化
for(int k = 1; k <= n; k++) { //尝试经过 k 个点对每对顶点之间的距离进行更新
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];//存距离
path[i][j] = path[i][k];//存路径
}
}
}
}
}
int pfpath(int u, int v) { //打印最短路径
while(u != v) {
cout << u << " ";
u = path[u][v];
}
cout << u << endl;
}
int main() {
int n, m;
while(cin >> n >> m){ // n 个点, m 条边
for(int i = 0; i <= n; i++) for(int j = -1; j <= n; j++){
dist[i][j] = (i == j ? 0 : INF);
}
for(int i = 0; i < m; i++) {
int u, v, w; cin >> u >> v >> w;
dist[u][v]=w; //无向图
//dist[u][v] = dist[v][u] = w; //无向图
}
floyd(n, dist);
cout<<dist[4][3]<<endl; // 4到3的最短距离
pfpath(4,3);//4到3的最短路径
}
return 0;
}
输入
//点数,边数
//a点,b点,ab距离
4 8
1 2 2
1 3 6
1 4 4
2 3 3
3 1 7
3 4 1
4 1 5
4 3 12
输出
//4到3的最短距离和路径
10
4 1 2 3