B3647 Floyed 题解

· · 个人记录

本题考查最短路径算法Floyed,根据数据量n<=10可推断本题使用时间的复杂度n^3的Floyed并不会超时。
值得注意的是,Floyed算法核心部分中,最外层循环为代表松弛的变量!

# include <bits/stdc++.h>
using namespace std;
const int inf=0x3f;
const int maxn=105;
int dist[maxn][maxn];
int n,m;
int main()
{
    scanf("%d%d",&n,&m);
    memset(dist,inf,sizeof(dist));
    for (int i=1;i<=n;i++)
    {
        dist[i][i]=0;
    }
    //the map should be started filled with inf and 0
    for (int i=1;i<=m;i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        dist[u][v]=min(dist[u][v],w); //PAY ATTENTION the data have some edges which occur many times
        dist[v][u]=dist[u][v]; // two_direction
    }
    //Floyed
    for (int k=1;k<=n;k++)
    {
        for (int i=1;i<=n;i++)
        {
            for (int j=1;j<=n;j++)
            {
                dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
            }
        }
    }
    //Output
    for (int i=1;i<=n;i++)
    {
        for (int j=1;j<=n;j++)
        {
            printf("%d ",dist[i][j]);
        }
        printf("\n");
    }
    return 0;
}