• 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 的最短路径的路径以及值)
    */

  • 相关阅读:
    课程作业06-汇总整理
    课程作业04-汇总整理
    课程作业04-字串加密解密
    课程作业03-你已经创建了多少个对象?
    课程作业03-汇总整理
    课程作业02-汇总整理
    02-实验性问题总结归纳
    猜数字游戏
    RandomStr实验报告(验证码实验)
    个人总结
  • 原文地址:https://www.cnblogs.com/robbychan/p/3787205.html
Copyright © 2020-2023  润新知