hdoj 2544 最短路(最短路+Dijkstrea算法)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544

思路分析:该问题给定一个无向图,要求求从起始点到终点的最短路径长度;可以使用dijkstra算法求出该起始点到其他所有点的最短距离;

 

代码如下:

#include <queue>
#include <climits>
#include <cstdio>
#include <vector>
#include <utility>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std;

typedef pair<int, int> PII;
const int MAX_N = 10000 + 10;
const int MAX_M = 100 + 10;
int u[MAX_N], v[MAX_N], w[MAX_N];
bool done[MAX_N];
int d[MAX_N];
vector<PII> G[MAX_N];

void Dijkstra(int n)
{
    priority_queue<PII, vector<PII>, greater<PII> > q;

    for (int i = 1; i <= n; ++i)
        d[i] = (i == 1 ? 0 : INT_MAX);
    memset(done, NULL, sizeof(done));
    q.push(make_pair(d[1], 1));
    while (!q.empty())
    {
        PII x = q.top();
        q.pop();
        int u = x.second;
        if (done[u]) continue;
        done[u] = true;
        for (int i = 0; i < G[u].size(); ++i)
        {
            int v = G[u][i].first;
            int w = G[u][i].second;
            if (d[v] > d[u] + w)
            {
                d[v] = d[u] + w;
                q.push(make_pair(d[v], v));
            }
        }
    }
}

int main()
{
    int N, M;

    while (scanf("%d %d", &N, &M) != EOF && N && M)
    {
        for (int e = 1; e <= M; ++e)
        {
            scanf("%d %d %d", &u[e], &v[e], &w[e]);
            G[u[e]].push_back(make_pair(v[e], w[e]));
            G[v[e]].push_back(make_pair(u[e], w[e]));
        }
        Dijkstra(N);
        printf("%d\n", d[N]);
        for (int i = 0; i <= N; ++i)
            G[i].clear();
    }
    return 0;
}

 

posted @ 2015-07-26 16:25  Leptus  阅读(190)  评论(0编辑  收藏  举报