Floyd算法

详细讲解:
 
例题:
Problem Description
在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt。但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店到赛场的路线,你可以帮助他们吗?
 
Input
输入包括多组数据。每组数据第一行是两个整数N、M(N<=100,M<=10000),N表示成都的大街上有几个路口,标号为1的路口是商店所在地,标号为N的路口是赛场所在地,M则表示在成都有几条路。N=M=0表示输入结束。接下来M行,每行包括3个整数A,B,C(1<=A,B<=N,1<=C<=1000),表示在路口A与路口B之间有一条路,我们的工作人员需要C分钟的时间走过这条路。 输入保证至少存在1条商店到赛场的路线。
 
Output
对于每组输入,输出一行,表示工作人员从商店走到赛场的最短时间
 
Sample Input
2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0
 
Sample Output
3
2
 
hdu ac代码:
 
#include<iostream>
#include<cstring>
#define INF 0xfffffff

using namespace std;

int dist[110][110];

int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)break;
//        memset(dist,INF,sizeof(dist));
        for(int i=1;i<=109;i++)
            for(int j=1;j<=109;j++)
        {
            dist[i][j]=INF;
        }

        for(int i=1;i<=n;i++)
        {
            dist[i][i]=0;
        }
//
//        cout<<dist[1][2]<<endl;
//        cout<<dist[3][2]<<endl;

        for(int i=1;i<=m;i++)
        {
            int a,b,c;
            cin>>a>>b>>c;
            dist[a][b]=c;
            dist[b][a]=c;
        }

        for(int k=1;k<=n;k++)
            for(int i=1;i<=n;i++)
                for(int j=1;j<=n;j++)
            {
                int temp=(dist[i][k]==INF||dist[k][j]==INF)?INF:(dist[i][k]+dist[k][j]);
                if(temp<dist[i][j])
                {
                    dist[i][j]=temp;
                    dist[j][i]=temp;
                }
            }
        cout<<dist[1][n]<<endl;
    }
}
 
注意事项:
二维数组初始化无穷大值时,用memset函数没有效果,原因不明,可以用两个for循环逐一赋值。
在读入最初两点间距离时,要将对应的矩阵因素赋上相同的值,即dist[a][b]=c;dist[b][a]=c;
在更新最短距离时,也要做相同的事情。
dist[i][j]=temp;
dist[j][i]=temp;


 
原文地址:https://www.cnblogs.com/cross-yan/p/7209716.html