最短路径算法

#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;
}

猜你喜欢

转载自www.cnblogs.com/achao123456/p/9187517.html