kyopro_library

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

View the Project on GitHub dyktr06/kyopro_library

:heavy_check_mark: test/library_checker/data_structure/unionfind.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/unionfind"
#include <bits/stdc++.h>
using namespace std;

#include "../../../lib/data_structure/union_find.hpp"

int main(){
    int n, q; cin >> n >> q;
    UnionFind tree(n);
    while(q--){
        int t, u, v; cin >> t >> u >> v;
        if(t == 0){
            tree.unite(u, v);
        }else{
            if(tree.same(u, v)){
                cout << 1 << "\n";
            }else{
                cout << 0 << "\n";
            }
        }
    }
}
#line 1 "test/library_checker/data_structure/unionfind.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/unionfind"
#include <bits/stdc++.h>
using namespace std;

#line 2 "lib/data_structure/union_find.hpp"

/**
 * @brief Union-Find
 * @docs docs/data_structure/union_find.md
 */

#line 10 "lib/data_structure/union_find.hpp"

struct UnionFind{
    int V;
    std::vector<int> par;
    std::vector<int> edg;

    UnionFind(const int N) : V(N), par(N), edg(N){
        for(int i = 0; i < N; ++i){
            par[i] = -1;
            edg[i] = 0;
        }
    }

    int root(int x){
        assert(0 <= x && x < V);
        if(par[x] < 0) return x;
        return par[x] = root(par[x]);
    }

    int unite(int x, int y){
        int rx = root(x);
        int ry = root(y);
        if(rx == ry){
            edg[rx]++;
            return rx;
        }
        if(-par[rx] < -par[ry]) std::swap(rx, ry);
        par[rx] = par[rx] + par[ry];
        par[ry] = rx;
        edg[rx] += edg[ry] + 1;
        return rx;
    }

    bool same(int x, int y){
        int rx = root(x);
        int ry = root(y);
        return rx == ry;
    }

    long long size(int x){
        return -par[root(x)];
    }

    long long edge(int x){
        return edg[root(x)];
    }
};
#line 6 "test/library_checker/data_structure/unionfind.test.cpp"

int main(){
    int n, q; cin >> n >> q;
    UnionFind tree(n);
    while(q--){
        int t, u, v; cin >> t >> u >> v;
        if(t == 0){
            tree.unite(u, v);
        }else{
            if(tree.same(u, v)){
                cout << 1 << "\n";
            }else{
                cout << 0 << "\n";
            }
        }
    }
}
Back to top page