Table of contents
Introduction
First we need to know what is the shortest path from a to b
The shortest path from a to b is the minimum distance (cost) from point a to point b
The multi-source shortest path means that we can find the shortest path between any a and b.
Then Folyd is the shortest path from multiple sources, that is, finding the shortest path between any a and b.
accomplish
First introduce a term " relaxation "
What does relaxation mean? The shortest path of this point is updated. It can be updated by one point or by b-connected changes (dijkstra and bellman-ford and spfa)
So what is Floyd’s thinking?
- Choose a k
- Choose a
- Choose a b
- relax a->b
Oh, by the way, some friends guessed it, triple cycle! ! ! Keep it simple
By now you should know how to write code, right?
Friends who still don’t know how to do it, come with me.
code
#include <iostream>
#include <cstring>
using namespace std;
const int N = 5e2 + 5;
int n, m;
int G[N][N]; //邻接矩阵
void Floyd() {
for (int k = 1; k <= n; k ++)
for (int a = 1; a <= n; a ++)
for (int b = 1; b <= n; b ++)
G[a][b] = min(G[a][b], G[a][k] + G[k][b]);
}
int main() {
cin >> n >> m;
memset(G, 0x3f, sizeof G);
for (int i = 1; i <= m; i ++) {
int a, b, c;
cin >> a >> b >> c;
G[a][b] = c; // a到b 距离为c
}
for (int i = 1; i <= n; i ++)
G[i][i] = 0;//自己到自己为0
Floyd();
// for (int i = 1; i <= n; i ++) {
// for (int j = 1; j <= n; j ++)
// cout << G[i][j] << ' ';
// cout << '\n';
// }
int a, b;
cin >> a >> b;
cout << G[a][b];
return 0;
}