Library

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

View the Project on GitHub maguroplusia/Library

:heavy_check_mark: Graph/Kruskal.cpp

Depends on

Verified with

Code

#include"../DataStructure/UnionFind.cpp"

struct edge {
    int u,v;
    long long cost;

    bool operator<(const edge& b) const {
        return cost < b.cost;
    }
};

int N,M;
edge graph[200010];

long long Kruskal() {
    sort(graph,graph + M);
    UnionFind uf(N);
    long long ret = 0;
    for(int i = 0;i < M;i++) {
        edge e = graph[i];
        if(!uf.same(e.u,e.v)) {
            uf.unite(e.u,e.v);
            ret += e.cost;
        }
    }
    return ret;
}
#line 1 "DataStructure/UnionFind.cpp"
class UnionFind {
    vector<int> par;
    vector<int> siz;

public:

    UnionFind(int n) {
        par.resize(n);
        siz.resize(n);
        for(int i = 0;i < n;i++) {
            par[i] = i;
            siz[i] = 1;
        }
    }

    int find(int x) {
        if(par[x] == x) {
            return x;
        }
        else {
            return par[x] = find(par[x]);
        }
    }

    void unite(int x,int y) {
        x = find(x);
        y = find(y);
        if(x == y) {
            return;
        }
        if(siz[x] < siz[y]) {
            swap(x,y);
        }
        par[y] = x;
        siz[x] += siz[y];
    }

    bool same(int x,int y) {
        return find(x) == find(y);
    }

    int size(int x) {
        return siz[find(x)];
    }
};
#line 2 "Graph/Kruskal.cpp"

struct edge {
    int u,v;
    long long cost;

    bool operator<(const edge& b) const {
        return cost < b.cost;
    }
};

int N,M;
edge graph[200010];

long long Kruskal() {
    sort(graph,graph + M);
    UnionFind uf(N);
    long long ret = 0;
    for(int i = 0;i < M;i++) {
        edge e = graph[i];
        if(!uf.same(e.u,e.v)) {
            uf.unite(e.u,e.v);
            ret += e.cost;
        }
    }
    return ret;
}
Back to top page