Floyd 求多源最短路径模板

 代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=1005;
const int INF=0x3f3f3f3f;
int mapp[maxn][maxn];
int d[maxn][maxn];
int path[maxn][maxn];
int t,n;
//Floyd算法
void Floyd()
{
    for (int i=1;i<=n;i++)
        for (int j=1;j<=n;j++)
            d[i][j]=mapp[i][j];
    for (int k=1;k<=n;k++)
        for (int i=1;i<=n;i++)
           for (int j=1;j<=n;j++)
               if(d[i][k]+d[k][j]<d[i][j]) //核心部分
                    {
                        d[i][j]=d[i][k]+d[k][j];
                        path[i][j]=k;
                    }
}
//找路径
void step(int s,int e)
{
    if(path[s][e]==-1)
    {
        printf("%d->",s);
        return;
    }
    else
    {
        step (s,path[s][e]);
        step (path[s][e],e);
    }

}
int main()
{
    //n表示城市数,t表示路径长度
    scanf("%d%d",&n,&t);
    memset (path,-1,sizeof(path));
    for (int i=1;i<=n;i++)
        for (int j=1;j<=n;j++)
            {
                if(i==j)
                    mapp[i][j]=0;
                else
                    mapp[i][j]=INF;
            }
    for (int i=0;i<t;i++)
    {
        int x,y,len;
        scanf("%d%d%d",&x,&y,&len);
        mapp[x][y]=mapp[y][x]=len;
    }
    Floyd();
    for (int i=2;i<=n;i++)
    {
        printf("1->%d 长度为:\n",i);
        printf("%d\n",d[1][i]);
        printf("路径为:\n");
        step (1,i);
        printf("%d\n",i);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/81429462
今日推荐