aoj

DSL_1_A: Disjoint Set: Union Find Tree

DSL_1_A: Disjoint Set: Union Find Tree
Feb. 2, 2020, 1:52 p.m.

目次

解答

{{ $t('desc') }}

コード

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#define MAX_N 10000
#define MAX_Q 100000

#define UNITE 0
#define SAME 1

Int ds_rank[MAX_N];
Int parent[MAX_N];


Int root(Int x) {
    if (x != parent[x]) {
        parent[x] = root(parent[x]);
    }

    return parent[x];
}

void unite(Int x, Int y) {
    Int x_root = root(x), y_root = root(y);

    if (ds_rank[x_root] > ds_rank[y_root]) {
        parent[y_root] = x_root;
    } else {
        parent[x_root] = y_root;
        if (ds_rank[x_root] == ds_rank[y_root]) ds_rank[y_root]++;
    }
}

bool same(Int x, Int y) {
    return root(x) == root(y);
}

int main(void) {
    int n, q, com, x, y;
    cin >> n >> q;

    loop(i,0,n) ds_rank[i] = 0, parent[i] = i;

    loop(i,0,q) {
        cin >> com >> x >> y;
        if (com == UNITE) unite(x, y);
        else {
            if (same(x, y)) cout << 1 << endl;
            else cout << 0 << endl;
        }
    }
}