hdoj 1874 畅通工程续(单源最短路+dijkstra)

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

思路分析:该问题给定一个无向图、起始点和终点,要求求出从起始点到终点的最短距离;

使用Dijkstra算法求出从起始点到所有的其他点的最短路长度即可,如果最短路长度为INT_MAX,表示从起始点到该点没有路径相连;

 

代码如下:

#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 start, int n)
{
    priority_queue<PII, vector<PII>, greater<PII> > q;

    for (int i = 0; i < n; ++i)
        d[i] = (i == start ? 0 : INT_MAX);
    memset(done, NULL, sizeof(done));
    q.push(make_pair(d[start], start));
    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)
    {
        int start, end;
        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]));
        }
        scanf("%d %d", &start, &end);
        Dijkstra(start, N);
        if (d[end] == INT_MAX)
            d[end] = -1;
        printf("%d\n", d[end]);
        for (int i = 0; i < N; ++i)
            G[i].clear();
    }
    return 0;
}

你可能感兴趣的:(dijkstra)