- 算法说明
Floyd主要来刷新两点之间的距离,三重循环
- 源代码
#include <cstdio>
#include <algorithm>
using namespace std;
#define INF 1 << 20
#define maxn 100 + 1
int n, m, a, b, c;
int G[maxn][maxn];
void output(){
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(i != j) {
if(G[i][j] == INF) printf("INF ");
else printf(" %-3d", G[i][j]);
}
else printf(" 0 ");
}
printf("\n");
}
printf("\n");
}
int main() {
freopen("2.floyd’sAlgorithmAllPairsShortestPaths.txt", "r", stdin);
freopen("2.floyd’sAlgorithmAllPairsShortestPathsOutput.txt", "w", stdout);
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) fill(G[i], G[i] + n + 1, INF);
while(m--) {
scanf("%d%d%d", &a, &b, &c);
G[a][b] = c;
}
output();
for(int k = 1; k <= n; k++) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
int ij = G[i][k] + G[k][j];
if(G[i][j] > ij) G[i][j] = ij;
}
}
}
output();
return 0;
}
- 输入数据
- 运行结果