cpplib

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

View the Project on GitHub morioprog/cpplib

:heavy_check_mark: クラスカル法
(graph/minimumspanningtree/kruskal.hpp)

概要

最小全域木を求めるアルゴリズム. 内部でUnionFindを使用している.

計算量

$O(E\log V)$

使用例

Verified with

Code

/**
* @brief クラスカル法
* @docs docs/graph/minimumspanningtree/kruskal.md
*/

template <typename T>
T kruskal(const Graph<T> &g) {
    vector<Edge<T>> edges;
    for (int i = 0; i < g.V; ++i)
        for (auto &e : g.mat[i]) edges.emplace_back(e);
    sort(edges.begin(), edges.end(), [](const Edge<T> &a, const Edge<T> &b) {
        return a.cst < b.cst;
    });
    UnionFind uf(g.V);
    T ret(0);
    for (auto &e : edges)
        if (uf.unite(e.frm, e.to)) ret += e.cst;
    return ret;
}
#line 1 "graph/minimumspanningtree/kruskal.hpp"
/**
* @brief クラスカル法
* @docs docs/graph/minimumspanningtree/kruskal.md
*/

template <typename T>
T kruskal(const Graph<T> &g) {
    vector<Edge<T>> edges;
    for (int i = 0; i < g.V; ++i)
        for (auto &e : g.mat[i]) edges.emplace_back(e);
    sort(edges.begin(), edges.end(), [](const Edge<T> &a, const Edge<T> &b) {
        return a.cst < b.cst;
    });
    UnionFind uf(g.V);
    T ret(0);
    for (auto &e : edges)
        if (uf.unite(e.frm, e.to)) ret += e.cst;
    return ret;
}
Back to top page