跳到正文

算法·理论

【图论 - 04】Dijkstra

Ydch约 7 分钟
原文

这是 2026年5月2日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

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

版本

  1. v2当前
  2. v1

P1. Dijkstra

Dijkstra 适用于无负权值的图中。

Dijkstra 的思想就是维护一个顶点集合 CC,在 CC 中的顶点都已经找到了最短路,而 Dijkstra 就是在每一轮迭代中找到离起点最近的点,让其加入 CC,并遍历连接的这个点进行松弛操作,当没有点加入 CC 或到达 TT 时,算法结束。

可以证明,第一次遍历到一个点一定是这个点的最短路,前提是无负权值。

那么知道了算法操作,接下来就是模拟了我们就可以写代码了。

例题:P4779 【模板】单源最短路径(标准版)

C++
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <climits>
#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()
#define inf 0xffffffff
using namespace std;

struct Node {
    int v, w;
};
vector<vector<Node> > g(100005);
vector<bool> flag(100005, false);  //记录是否在 C 中。
int n, m, S, dis[100005];

inline void Dijkstra() {
    fill(dis, dis + 100005, INT_MAX);  //初始化。
    flag.assign(100005, false);
    dis[S] = 0;   //起点为 0。
    while (true) {
        int x = -1;  //记录下标。
        for (int i = 1; i <= n; i++)
            if (!flag[i] && dis[i] < INT_MAX)  //没在 C 中且 dist 不是无穷大。
                if (x == -1 || dis[i] < dis[x])  //离起点更近或第一次遍历到。
                    x = i;
        if (x == -1)  //没有更新的点了,结束。
            break;
        flag[x] = true;  //添加进 C。
        for (Node u : g[x])
            dis[u.v] = min(dis[u.v], dis[x] + u.w);  //为连接的点做松弛操作。
    }
    for (int i = 1; i <= n; i++) cout << dis[i] << ' ';
}

signed main() {
    ios;
    cin >> n >> m >> S;
    for (int i = 1, x, y, z; i <= m; i++) {
        cin >> x >> y >> z;
        g[x].push_back({y, z});
    }
    Dijkstra();
    return 0;
}

时空复杂度:

第 3434 行的遍历点的复杂度为 O(n2)O(n^{2}),第 4040 行的循环遍历边的复杂度为 O(m)O(m),相加即为 O(n2+m)O(n ^ {2} + m)。

O(n2+m)O(n ^ {2} + m)?神秘 TLE,那么,请看优化。

P2. 优先队列优化

遍历点的 O(n2)O(n ^ {2}) 复杂度可以考虑使用优先队列优化,将复杂度降至 O((n+m)log⁡n)O((n + m) \log n)。

优先队列简单讲解:

队列内的内容自动从大到小排序,可使用重载运算符修改,出队时优先出队的是最大的数(默认情况下)。

C++
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <climits>
#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()
#define inf 0xffffffff
using namespace std;

struct Node {
    int v, w;
};

struct node {
    int d, u;
    bool operator < (const node &a) const {  //优先队列默认大数靠前,故重载运算符使小数靠前。
        return d > a.d;
    }
};

vector<vector<Node> > g(100005);
vector<bool> flag(100005, false);
int n, m, S, dis[100005];
priority_queue<node> q;

inline void Dijkstra() {
    fill(dis, dis + 100005, INT_MAX);  //初始化。
    flag.assign(100005, false);
    dis[S] = 0;
    q.push({0, S});   //加入队列。
    while (!q.empty()) {
        node t = q.top();
        q.pop();
        int u = t.u;
        if (flag[u]) continue;  //加入过 C 了,退出。
        flag[u] = true;   //标记。
        for (Node i : g[u]) {  //遍历 u 的邻接表。
            int v = i.v;
            int w = i.w;
            if (dis[v] > dis[u] + w) { //松弛操作。
                dis[v] = dis[u] + w;
                q.push({dis[v], v});  //加入队列。
            }
        }
    }
    for (int i = 1; i <= n; i++) cout << dis[i] << ' ';
}

signed main() {
    ios;
    cin >> n >> m >> S;
    for (int i = 1, x, y, z; i <= m; i++) {
        cin >> x >> y >> z;
        g[x].push_back({y, z});
    }
    Dijkstra();
    return 0;
}