HDU2544 最短路 题解 Bellman-Ford算法

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

题目大意:一道简单的最短路。主要是记录一下 bellman-ford 算法的实现。

示例程序(bellman-ford):

#include <bits/stdc++.h>
using namespace std;
const int maxn = 110, maxm = 20020;
int n, m, dis[maxn]; // , pre[maxn];
struct Edge {
    int u, v, w;
} edge[maxm];

int main() {
    while (~scanf("%d%d", &n, &m) && n) {
        memset(dis, 0x3f, sizeof(int)*(n+1));
//        memset(pre, 0, sizeof(int)*(n+1));
        dis[1] = 0;
        for (int i = 0; i < 2*m; i += 2) {
            int u, v, w;
            scanf("%d%d%d", &u, &v, &w);
            edge[i] = {u, v, w};
            edge[i+1] = {v, u, w};
        }
        m *= 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int u = edge[j].u, v = edge[j].v, w = edge[j].w;
                if (dis[v] > dis[u] + w) {
                    dis[v] = dis[u] + w;
                    // pre[v] = u;
                }
            }
        }
        printf("%d\n", dis[n]);
    }
    return 0;
}
posted @ 2024-01-03 16:42  quanjun  阅读(10)  评论(0编辑  收藏  举报