HDOJ 2544 最短路

http://acm.hdu.edu.cn/showproblem.php?pid=2544

题面:
最短路裸题。

Bellman-Ford算法:

//  Bellman-Ford最短路算法
#include <iostream>
#include <cstdlib>
#include <algorithm>
#define MAX_V 105
#define MAX_E 10005
#define INF 0x3f3f3f3f
using namespace std;

struct edge {
    int from, to;
    int cost;
};
edge g[MAX_E];
int d[MAX_V]; // d[i]表示d[start]到i点的最短距离
int v, e; // 顶点数, 边数
int start, to;

void Bellman_Ford(int s) {
    for (int i = 1; i <= v; ++i)
        d[i] = INF;
    d[s] = 0;
    bool update = true;
    while (update) {
        update = false;
        for (int i = 1; i <= 2 * e; ++i) {
            edge e = g[i];
            if (d[e.from] != INF && d[e.to] > d[e.from] + e.cost) {
                d[e.to] = d[e.from] + e.cost;
                update = true;
            }
        }
    }
}
int main() {
    while (cin >> v >> e && v && e) {
        for (int i = 1; i <= e; ++i) {
            int f, t, c;
            cin >> f >> t >> c;
            g[i].from = g[i + e].to = f;
            g[i].to = g[i + e].from = t;
            g[i].cost = g[i + e].cost = c;
        }
        Bellman_Ford(1);
        cout << d[v] << '\n';
    }
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 相信每一位玩ACM程序设计竞赛的同学来说,都有一个从入门到精通的过程,而且分享他们经验的时候,见到最多的就是一种合...
    FinlayLiu阅读 5,472评论 6 182
  • 作为一个前端程序猿,下面这些站会让你眼前一亮。 amazeui框架组建丰富 http://amazeui.org...
    欧巴冰冰阅读 8,946评论 18 303
  • 风光旖旎的八桂大地,风情万种的民族之乡,在这里,书写你爱它的一切理由…… 专题主编:路辰 广西专题投稿须知: 1、...
    路辰阅读 653评论 0 7
  • 在eclipse下写xml想对齐一下,发现没反应,但是课上老师是可以的,这是为什么。。。而中文输入法从简体变成繁体...
    shenyoujian阅读 1,166评论 0 0
  • 黑色的夜空 给人以深邃的思想 偶尔的光亮 将回忆带去远方 那是流星吗 不 那是理想 天才般闪亮 给人无尽欢畅 逝去...
    掬一丝微风阅读 193评论 0 0