ContinueLib

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

View the Project on GitHub Continue765/ContinueLib

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

prim

定义于头文件 prim.hpp

template <typename T, typename F>
vector<Edge<T>> prim(int n, F&& cost);  // (1)

template <typename T>
pair<vector<int>, T> prim(Undigraph<T>& g);  // (2)

求最小生成树。prim(n, cost) 返回生成树的 $n - 1$ 条边,prim(g) 返回 {res, cost}。

参数

参数 说明
n 点数
cost T cost(int u, int v),点 u、v 之间边的权值
g 无向图

返回值

prim(n, cost) 返回生成树的 $n - 1$ 条边;prim(g) 返回 {res, cost}:res 为选中的边编号,cost 为选中边的权值之和。

复杂度

$O(n^2)$。

示例

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

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

auto edges = prim<i64>(3, [](int u, int v) { return abs(u - v); });

Depends on

Verified with

Code

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

template <typename T, typename F>
vector<Edge<T>> prim(int n, F&& cost) {
    vector<Edge<T>> res;
    vector<T> wei(n, inf<T>);
    vector<int> pre(n);

    auto add = [&](int u) -> void {
        for (int v = 0; v < n; v++) {
            if (pre[v] == -1) {
                continue;
            }
            T w = cost(u, v);
            if (wei[v] > w) {
                wei[v] = w;
                pre[v] = u;
            }
        }
        wei[u] = inf<T>;
        pre[u] = -1;
    };

    add(0);
    for (int i = 0; i < n - 1; i++) {
        int u = min_element(wei.begin(), wei.end()) - wei.begin();
        res.emplace_back(pre[u], u, wei[u]);
        add(u);
    }

    return res;
}

template <typename T>
pair<vector<int>, T> prim(Undigraph<T>& g) {
    int n = g.n;
    vector<int> res, pre(n, -2);
    vector<T> wei(n, inf<T>);
    T cost = 0;
    auto add = [&](int u) -> void {
        for (auto& [v, id] : g[u]) {
            if (pre[v] == -1) {
                continue;
            }
            T w = g.edges[id].w;
            if (wei[v] > w) {
                wei[v] = w;
                pre[v] = id;
            }
        }
        wei[u] = inf<T>;
        pre[u] = -1;
    };
    add(0);
    for (int i = 0; i < n - 1; i++) {
        int u = min_element(wei.begin(), wei.end()) - wei.begin();
        if (wei[u] == inf<T>) {
            break;
        }
        res.push_back(pre[u]);
        cost += wei[u];
        add(u);
    }
    return {res, cost};
}
Back to top page