ContinueLib

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub Continue765/ContinueLib

:heavy_check_mark: spfa
(graph/shortest_path/spfa.hpp)

spfa

定义于头文件 spfa.hpp

template <typename T, bool dir>
pair<vector<T>, vector<int>> spfa(const Graph<T, dir>& g, int s);

求 g 中以 s 为源点的单源最短路,允许负权边,返回 {dist, pre};存在从 s 可达的负环时返回 { {}, {} }。

参数

参数 说明
g 有向或无向图
s 源点

返回值

返回 {dist, pre}:dist[v] 为 s 到 v 的最短距离,不可达为 inf<T>;pre[v] 为最短路树上 v 的前驱,v = s 或不可达时为 -1。

复杂度

最坏 $O(nm)$,$n$ 为点数,$m$ 为边数。

示例

Graph<int> g(n);
g.add(0, 1, 5);
g.add(1, 2, -3);
auto [dist, pre] = spfa(g, 0);

Depends on

Verified with

Code

#pragma once
#include <graph/graph.hpp>

template <typename T, bool dir>
pair<vector<T>, vector<int>> spfa(const Graph<T, dir>& g, int s) {
    int n = g.n;
    vector<T> dist(n, inf<T>);
    vector<int> pre(n, -1);

    dist[s] = 0;

    queue<int> q;
    vector<char> inq(n, false);
    vector<int> cnt(n, 0);
    q.push(s);
    inq[s] = true;

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        inq[u] = false;
        for (auto [v, id] : g[u]) {
            T w = g.edges[id].w;
            if (dist[v] > dist[u] + w) {
                dist[v] = dist[u] + w;
                pre[v] = u;
                if (!inq[v]) {
                    q.push(v);
                    inq[v] = true;
                    cnt[v]++;
                    if (cnt[v] >= n) {
                        return {{}, {}};
                    }
                }
            }
        }
    }

    return {dist, pre};
}
Back to top page