hdu 2544 最短路(dijkstra邻接矩阵)

/*

  Name: 最短路(dijkstra邻接矩阵) 

  Copyright: 

  Author: Try_86

  Date: 12/04/12 18:09

  Description: 

*/





#include <cstdio>

#include <cstring>

#include <iostream>



using namespace std;



const int N = 105;  

const int MAX = 1000000000;//定义无穷大 



bool vis[N];

int map[N][N], dis[N];



void init(int vs) {//初始化 

    for (int i=1; i<vs; ++i) {

        map[i][i] = 0;

        for (int j=i+1; j<=vs; ++j) map[i][j] = map[j][i] = MAX;

    }

    return ;

}



void dijkstra(int vs, int s) {

    memset(vis, false, sizeof(vis));

    int pos = s;

    vis[pos] = true;

    for (int i=1; i<=vs; ++i) dis[i] = map[pos][i];

    dis[pos] = 0;

    int minLen;

    for (int i=1; i<vs; ++i) {

        minLen = MAX;

        for (int j=1; j<=vs; ++j) {

            if (!vis[j] && minLen>dis[j]) minLen = dis[j], pos = j;

        }

        vis[pos] = true;

        for (int j=1; j<=vs; ++j) {

            int len = dis[pos]+map[pos][j];//松弛操作 

            if (!vis[j] && dis[j]>len) dis[j] = len;

        }

    }

    return ;

}



int main() {

    int n, m;

    while (scanf("%d%d", &n, &m), n+m) {

        init(n);

        int u, v, w;

        for (int i=0; i<m; ++i) {

            scanf ("%d%d%d", &u, &v, &w);

            if (map[u][v] > w) map[v][u] = map[u][v] = w;//去重边,并选择最短的一条 

        }

        dijkstra(n, 1);

        printf ("%d\n", dis[n]);

    }

    return 0;

}

 

你可能感兴趣的:(dijkstra)