📚Library

This documentation is automatically generated by competitive-verifier/competitive-verifier

View on GitHub

:heavy_check_mark: library/test/yosupo/unionfind.test.cpp

Depends on

Code

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

int main() {
    ios::sync_with_stdio(0);
    int n, q, typ, u, v;
    cin>>n>>q;
    DSU dsu(n);
    while(q--) {
        cin>>typ>>u>>v;
        if(typ) {
            cout<<dsu.connected(u, v)<<endl;
        } else {
            dsu.unite(u, v);
        }
    }
    return 0;
}
#line 1 "library/test/yosupo/unionfind.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/unionfind"
#include <bits/stdc++.h>
using namespace std;
#line 1 "library/ds/dsu.hpp"
struct DSU {
    vector<int> par;
    int cc; // connected components
    DSU(int n) : par(n, -1), cc(n) {}
    // get representive component (uses path compression)
    int get(int x) { return par[x] < 0 ? x : par[x] = get(par[x]); }
    // check whether a and b are in the same connected component
    bool connected(int a, int b) { return get(a) == get(b); }
    int size(int x) { return -par[get(x)]; }
    int groups() { return cc; } // number of groups
    int leader(int v) const {
        while (par[v] > -1)
            v = par[v];
        return v;
    }
    bool unite(int x, int y) { // union by size
        x = get(x), y = get(y);
        if (x == y)
            return false;
        cc--;
        if (par[x] > par[y])
            swap(x, y);
        par[x] += par[y];
        par[y] = x;
        return true;
    }
};
#line 5 "library/test/yosupo/unionfind.test.cpp"

int main() {
    ios::sync_with_stdio(0);
    int n, q, typ, u, v;
    cin>>n>>q;
    DSU dsu(n);
    while(q--) {
        cin>>typ>>u>>v;
        if(typ) {
            cout<<dsu.connected(u, v)<<endl;
        } else {
            dsu.unite(u, v);
        }
    }
    return 0;
}

Test cases

Env Name Status Elapsed Memory
g++ example_00 :heavy_check_mark: AC 7 ms 4 MB
g++ path_00 :heavy_check_mark: AC 123 ms 4 MB
g++ path_01 :heavy_check_mark: AC 101 ms 4 MB
g++ path_02 :heavy_check_mark: AC 37 ms 4 MB
g++ path_03 :heavy_check_mark: AC 36 ms 4 MB
g++ random_00 :heavy_check_mark: AC 103 ms 4 MB
g++ random_01 :heavy_check_mark: AC 110 ms 4 MB
g++ random_02 :heavy_check_mark: AC 86 ms 4 MB
g++ random_03 :heavy_check_mark: AC 24 ms 4 MB
g++ random_04 :heavy_check_mark: AC 71 ms 4 MB
g++ random_05 :heavy_check_mark: AC 98 ms 4 MB
g++ random_06 :heavy_check_mark: AC 80 ms 4 MB
g++ random_07 :heavy_check_mark: AC 14 ms 4 MB
g++ random_08 :heavy_check_mark: AC 39 ms 4 MB
g++ random_09 :heavy_check_mark: AC 136 ms 4 MB
Back to top page