跳到正文

算法·理论

【图论 - 03】Bellman-Ford

Ydch约 7 分钟
原文
文章信息与版本

文章信息

收录
2026年5月2日
更新
2026年5月2日
篇幅
约 7 分钟

版本

  1. v2当前
  2. v1

P1. 负环

之前在 图的基本概念 中没有说负环。

在权值可以为负时,就有可能出现一种情况,能刷最短路,例如一条路径,走完之后走过的路程长度为负,那么我只需要再走回去,再走回来,我的最短路长度就能一直减,理论上可以达到 −∞-\infty(不是说在有负环的图中没有最短路)。

P2. Bellman-Ford

Bellman-Ford 适用于有负权值的图中。

Bellman-Ford 的主要组成部分就是这个公式:

dist(u)=min⁡(dist(u),dist(v)+l(u,v))dist(u) = \min(dist(u), dist(v) + l(u, v))

我们称它为松弛操作,Bellman-Ford 就是在反复为所有点执行这个操作,直到这个操作一次都没有执行过,Bellman-Ford 算法结束。

让我们边看 Code 边理解吧!

C++
struct Edge {
    int u, v, w;  //u 是边的起点,v 是边的终点,w 是权值。
} edge[500005];  //存储边的数组。
int n, m, dis[500005], last[500005];  //dis 是距离,last[u] 是走到 u 的最短路里 u 最近的,上一个点。

inline int Bellman_Ford(int x, int y) {  //x 是起点,y 是终点。
    fill(dis, dis + 500005, inf);   //初始化距离数组,初始时所有点的距离都是无穷大。
    fill(last, last + 500005, 0);   //初始化 last 数组,初始时所有点的上一个点都是 0。
    dis[x] = 0;  //起点到自己的距离为 0。
    while (true) {
        bool flag = true;  //记录是否进行过松弛操作。
        for (int i = 1; i <= m; i++) {   //遍历所有边。
            int u = edge[i].u, v = edge[i].v, w = edge[i].w;
            if (dis[u] < inf) {   //如果 u 的距离不是无穷大,说明 u 可达。
                if (dis[u] + w < dis[v]) {  //松弛操作。
                    dis[v] = dis[u] + w;
                    last[v] = u;  //更新 v 的上一个点为 u。
                    flag = false;  //记录进行了松弛操作。
                }
            }
        }
        if (flag) break;  //没进行过松弛操作,退出循环。
    }
    return dis[y];  //返回最短路距离。
}

其实 last 数组的唯一作用就是输出路径,你需要输出 xx 的路径时,就需要访问 lastxlast_x,接着访问 lastlastxlast_{last_x},以此类推,直到起点。

我们接着分析时间复杂度,我们知道,最短路径至多经过 n−1n - 1 条边,也就是 n−1n - 1 轮迭代,每次迭代的时间是 mm 故算法复杂度是 O(nm)O(nm),但在有负环的情况下迭代次数会更多。

P2.1 SPFA

SPFA 是 Bellman-Ford 的队列优化算法,但是尴尬的是,这个算法可以被卡,且最坏复杂度与 Bellman-Ford 一样都是 O(nm)O(nm),故不再讲解。

其实是我不会。

P2.2 负环判断

既然我们知道 Bellman-Ford 在无负环情况下的最坏迭代次数是 n−1n - 1,我们能否利用复杂度来判断这个图中是否存在负环呢?

有负环的情况下,迭代次数会超出 n−1n - 1,那么在 n−1n - 1 轮迭代后,再进行一次迭代,判断是否进行过松弛操作,进行过即为有负环。

C++
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <iomanip>
#include <vector>
#include <string>
#include <cmath>
#include <queue>
#include <deque>
#include <set>
#include <map>
#define ios ios::sync_with_stdio(false), cin.tie(nullptr)
#define double long double
#define int long long
#define endl '\n'
#define all(x) x.begin(), x.end()
using namespace std;

struct Node {
    int u, v, w;
};

const int inf = 1e18;

int n, m;
vector<Node> g;
vector<int> dis(2005);

inline string Bellman_Ford() {
    dis.assign(2005, inf);   //我在之前的帖子讲解过,assign ≈ fill。
    dis[1] = 0;   //第一个点设为 0。
    for (int T = 1; T <= n - 1; T++) {  //先进行 n - 1 次迭代。
        bool flag = true;    //和前面讲的 Bellman-Ford 没区别。
        for (int i = 0; i < g.size(); i++) {
            int u = g[i].u, v = g[i].v, w = g[i].w;
            if (dis[u] < inf && dis[u] + w < dis[v]) {
                dis[v] = dis[u] + w;
                flag = false;
            }
        }
        if (flag) break;
    }
    bool flag = false;  //再进行一次迭代,使用 flag 记录是否进行松弛操作。
    for (int i = 0; i < g.size(); i++) {
        int u = g[i].u, v = g[i].v, w = g[i].w;
        if (dis[u] < inf && dis[u] + w < dis[v]) {
            flag = true;  //进行了松弛操作。
            break;
        }
    }
    return (flag ? "YES" : "NO");  //返回结果。
}

void solve() {
    cin >> n >> m;
    g.clear();
    for (int i = 1, u, v, w; i <= m; i++) {
        cin >> u >> v >> w;
        if (w >= 0) {
            g.push_back({u, v, w});
            g.push_back({v, u, w});
        }
        else
            g.push_back({u, v, w});
    }
    cout << Bellman_Ford() << '\n';
}

signed main() {
    ios;
    int T = 1;
    cin >> T;
    while (T--) solve();
    return 0;
}
原文