HDU1874 畅通工程续

问题链接:HDU1874 畅通工程续

问题描述参见上文。

问题分析:这是一个经典的单源最短路径问题,使用Dijkstra算法

程序说明:图的表示主要有三种形式,一是邻接表,二是邻接矩阵,三是边列表。邻接矩阵对于结点多和边少的情况都不理想。程序中用邻接表存储图,即g[],是一种动态的存储。数组dist[]中存储单源(结点s)到各个结点的最短距离。优先队列q按照边的权值从小到大排队,便于计算最短路径。

这个问题,由于结点数量比较少,图还可以用邻接矩阵表示。那样的话,代码则是另外一种写法。

需要注意的一点是,有可能不存在路径,程序中93行增加条件“dist[t]==INT_MAX2”进行判断。

AC的C++语言程序如下:

/* HDU1874 畅通工程续 */

#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>

using namespace std;

const int INT_MAX2 = ((unsigned int)(-1) >> 1);
const int MAXN = 200;

// 边
struct _edge {
    int v, cost;
    _edge(int v2, int c){v=v2; cost=c;}
};

// 结点
struct _node {
    int u, cost;
    _node(){}
    _node(int u2, int l){u=u2; cost=l;}

    bool operator<(const _node n) const {
        return cost > n.cost;
    }
};

vector<_edge> g[MAXN+1];
int dist[MAXN+1];
bool visited[MAXN+1];

void dijkstra(int start, int n)
{
    priority_queue<_node> q;

    for(int i=0; i<=n; i++) {
        dist[i] = INT_MAX2;
        visited[i] = false;
    }

    dist[start] = 0;

    q.push(_node(start, 0));

    _node f;
    while(!q.empty()) {
        f = q.top();
        q.pop();

        int u = f.u;
        if(!visited[u]) {
            visited[u] = true;

            int len = g[u].size();
            for(int i=0; i<len; i++) {
                int v2 = g[u][i].v;

                if(visited[v2])
                    continue;

                int tempcost = g[u][i].cost;
                int nextdist = dist[u] + tempcost;

                if(dist[v2] > nextdist) {
                    dist[v2] = nextdist;
                    q.push(_node(v2, dist[v2]));
                }
            }
        }
    }
}

int main()
{
    int n, m, src, dest, cost2, s, t;

    // 输入数据,构建图
    while(scanf("%d%d",&n,&m) != EOF && (n + m)) {
        for(int i=1; i<=m; i++) {
            scanf("%d%d%d", &src, &dest, &cost2);

            g[src].push_back(_edge(dest, cost2));
            g[dest].push_back(_edge(src, cost2));
        }
        scanf("%d%d", &s, &t);

        // Dijkstra算法
        dijkstra(s, n);

        // 输出结果
        printf("%d\n", (dist[t] == INT_MAX2) ? -1 : dist[t]);

        // 释放存储
        for(int i=0; i<=n; i++)
            g[i].clear();
    }

    return 0;
}


posted on 2017-03-09 09:32  海岛Blog  阅读(115)  评论(0编辑  收藏  举报

导航