首页 > 其他 > 详细

Floy

时间:2019-09-01 22:42:56      阅读:72      评论:0      收藏:0      [点我收藏+]

多元最短路——Floyd

思路:枚举起点终点和中转点

 

变量:

int m, dis[N][N], n;

 

m条边,n个点,dis[i][j]数组储存从i到j的最短路径

 

 

主体:

 

void Folyd() {
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                if (dis[i][j] > dis[i][k] + dis[k][j])
                    dis[i][j] = dis[i][k] + dis[k][j];
    return;
}

 

 

分解一下。。。

 

        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)

for循环枚举从i到j的路径

 

枚举中转点

for (int k = 1; k <= n; k++)

 

完整代码:

 

#include <iostream>
#include <cstdio>
#define N 1001
#define INF 233

int m, dis[N][N], n;

void Folyd() {
    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                if (dis[i][j] > dis[i][k] + dis[k][j])
                    dis[i][j] = dis[i][k] + dis[k][j];
    return;
}

int main()
{
    scanf("%d %d", &n, &m);    
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) {
            dis[i][j] = INF;
            if (i == j)
                dis[i][j] = 0;
        } 
    for (int i = 1; i <= m; i++) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        dis[a][b] = c;
    }
    Folyd();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            printf("%5d", dis[i][j]);
        }
        printf("\n\n");
    }

    return 0;
}

 

Floy

原文:https://www.cnblogs.com/mynygtfl/p/11443801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!