HDOJ-2544 最短路(Dijkstra)

单源最短路径问题(感觉和Prime算法很像)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <climits>

using namespace std;
#define maxn 105
int Graph[maxn][maxn];
int dis[maxn], mark[maxn];
int main()
{
    //freopen("in.txt", "r", stdin);
    int n, m;

    while(cin >> n >> m)
    {
        if(n == 0 && m == 0)
          break;
        if(m == 0)
        {
            cout << 0 << endl;
            continue;
        }
        memset(mark, 0, sizeof(mark));
        memset(Graph, -1, sizeof(Graph));
        for(int i = 1; i <= n; i++)
        {
            dis[i] = INT_MAX;
        }
        for(int i = 1; i <= m; i++)
        {
            int a, b, c;

            scanf("%d%d%d", &a, &b, &c);
            Graph[a][b] = Graph[b][a] = c;
        }
        mark[1] = 1;
        int k = 1;
        for(int i = 2; i <= n; i++)
        {
            if(Graph[k][i] > 0)
             dis[i] = Graph[k][i];
        }
        for(int i = 2; i <= n; i++)
        {
            int mins = INT_MAX;

            for(int j = 2; j <= n; j++)
            {
                if(!mark[j] && dis[j] < mins)
                {
                    mins = dis[j];
                    k = j;
                }
            }
            mark[k] = 1;

            for(int j = 2; j <= n; j++)
            {
                if(!mark[j] && Graph[k][j] > 0)
                {
                    int t = Graph[k][j] + dis[k];

                    if(t < dis[j])
                     dis[j] = t;
                }
            }
        }
        cout << dis[n] << endl;
    }
    return 0;
}

你可能感兴趣的:(HDOJ-2544 最短路(Dijkstra))