首页 > 学院 > 开发设计 > 正文

HDU3790 最短路径问题

2019-11-06 07:51:47
字体:
来源:转载
供稿:网友

问题链接:HDU3790 最短路径问题。

问题描述:参见上文。

问题分析:这是一个最优化的问题,也是一个单源最短路径问题,所有要用Dijkstra算法。

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

与此同时,数组cost[i]中存储单源(结点s)到各个结点的最花费。需要注意的是,路径距离相同时,需要选择花费最小(76行代码)。

程序中,在Dijkstra算法基础上增加了72行和76行代码。

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

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

/* HDU3790 最短路径问题 */#include <iostream>#include <vector>#include <queue>#include <cstdio>using namespace std;const int INT_MAX2 = ((unsigned int)(-1) >> 1);const int MAXN = 10000;// 边struct _edge {    int v, length, cost;    _edge(int v2, int l, int c){v=v2; length=l; cost=c;}};// 结点struct _node {    int u, length;    _node(){}    _node(int u2, int l){u=u2; length=l;}    bool Operator<(const _node n) const {        return length > n.length;    }};vector<_edge> g[MAXN+1];int dist[MAXN+1];int cost[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;        cost[i] = INT_MAX2;        visited[i] = false;    }    dist[start] = 0;    cost[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 templength = g[u][i].length;                int nextdist = dist[u] + templength;                int tempcost = g[u][i].cost;                if(dist[v2] > nextdist) {                    dist[v2] = nextdist;                    cost[v2] = cost[u] + tempcost;                      // add code                    q.push(_node(v2, dist[v2]));                } else if(dist[v2] == nextdist) {                    // 距离相同则取花费少的                    cost[v2] = min(cost[v2], cost[u] + tempcost);         // add code                }            }        }    }}int main(){    int n, m, src, dest, len, cost2, s, t;    // 输入数据,构建图    while(scanf("%d%d",&n,&m) != EOF && (n + m)) {        for(int i=1; i<=m; i++) {            scanf("%d%d%d%d", &src, &dest, &len, &cost2);            g[src].push_back(_edge(dest, len, cost2));            g[dest].push_back(_edge(src, len, cost2));        }        scanf("%d%d", &s, &t);        // Dijkstra算法        dijkstra(s, n);        printf("%d %d/n", dist[t], cost[t]);        // 释放存储        for(int i=0; i<=n; i++)            g[i].clear();    }    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表