ContinueLib

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

View the Project on GitHub Continue765/ContinueLib

:heavy_check_mark: boruvka
(graph/mst/boruvka.hpp)

boruvka

定义于头文件 boruvka.hpp

template <typename T>
pair<vector<int>, T> boruvka(Undigraph<T>& g);

求无向图 g 的最小生成森林,返回 {res, cost}。

参数

参数 说明
g 无向图

返回值

返回 {res, cost}:res 为选中的边编号,cost 为选中边的权值之和。

复杂度

$O(m \log n)$,$n$ 为点数,$m$ 为边数。

示例

Undigraph<i64> g(4);
g.add(0, 1, 3);
g.add(1, 2, 1);
g.add(2, 3, 2);

auto [ids, cost] = boruvka(g);

Depends on

Verified with

Code

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

template <typename T>
pair<vector<int>, T> boruvka(Undigraph<T>& g) {
    auto& edges = g.edges;
    int n = g.n;
    T cost = 0;
    vector<int> res;
    DSU dsu(n);
    int cnt = n;

    while (cnt > 1) {
        vector<int> best(n, -1);
        int m = edges.size();

        for (int i = 0; i < m; i++) {
            auto& e = edges[i];
            int u = dsu.find(e.u);
            int v = dsu.find(e.v);
            if (u == v) {
                continue;
            }
            if (best[u] == -1 || e.w < edges[best[u]].w) {
                best[u] = i;
            }
            if (best[v] == -1 || e.w < edges[best[v]].w) {
                best[v] = i;
            }
        }

        bool upd = false;
        for (int u = 0; u < n; u++) {
            if (best[u] == -1) {
                continue;
            }
            auto& e = edges[best[u]];
            if (dsu.merge(e.u, e.v)) {
                res.push_back(best[u]);
                cost += e.w;
                cnt--;
                upd = true;
            }
        }
        if (!upd) {
            break;
        }
    }

    return {res, cost};
}
Back to top page