最短路径算法

#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
    int stations[31][31];
    int m,n,f,t,c;
    const int INF = 0x7fffffff;
    while(scanf("%d%d",&m,&n) != EOF){
        for(int i = 0; i <= n; i++){
            for(int j = 0; j <= n; j++) stations[i][j] = INF;
        }
        for(int i = 0; i < m; i++){
            scanf("%d%d%d",&f,&t,&c);
            stations[f][t] = c;
        }
        for(int k = 1; k <= n; k++){
            for(int i = 0; i <= n; i++){
                for(int j = 0; j <= n; j++){        
                    if(k != i && k != j && i != j && stations[i][k] != INF && stations[k][j] != INF){
                            stations[i][j] = min(stations[i][j],stations[i][k]+stations[k][j]);
                    }
                }
            }
        }
        printf("%d\n",stations[0][n]);
    }
    return 0;
}

 

posted on 2018-06-15 15:26  HelloWorldTotti  阅读(173)  评论(0编辑  收藏  举报

导航