Floydtemplate 示例

#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define BUG cout << "here\n";

using namespace std;
const int INF = 0x7fffffff;
const int N = 105;
int map[N][N];
int path[N][N];
int n, m;
int s, t;
void output(int i, int j){
    if(i == j) return;
    if(path[i][j] == -1) {
        cout << '-' << j;
    }
    else {
        output(i,path[i][j]);
        output(path[i][j],j);
    }
}
void solve(int a, int b) {
    BUG;
    s = a; t = b;
    cout << s;
    output(s, t);
    cout << " : " << map[s][t] << endl;
}
void floyd(int n) {
    int i, j, k;
    for(k = 1; k <= n; k++) {
        for(i = 1; i <= n; i++) {
            for(j = 1; j <= n; j++) {
                if(map[i][k] < INF && map[k][j] < INF && map[i][j] > map[i][k] + map[k][j]) {
                    map[i][j] = map[i][k] + map[k][j];
                    path[i][j] = k;
                }
            }
        }
    }
}

int main() {
    int i, j, a, b, w;
    while(cin >> n >> m) {
        for(i = 1; i <= n; i++) {
            for(j = 1; j <= n; j++) {
                if(i == j) map[i][j] = 0;
                map[i][j] = INF;
            }
        }
        for(i = 1; i <= m; i++) {
            cin >> a >> b >> w;
            map[a][b] = w;
        }
        memset(path, -1, sizeof(path));
        floyd(n);
        solve(1, 2);
    }
    return 0;
}
/*
测试数据
5 5
1 2 10
1 4 20
1 5 1
3 2 3
5 3 2
*/
/*
1-5-3-2 : 6   (表示 1 -> 2 的最短路径的路径以及值)
*/

原文地址:https://www.cnblogs.com/robbychan/p/3787205.html