Cod sursa(job #2576036)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 6 martie 2020 16:54:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 100005;
int n, m, key, x, y, parent[len], level[len];

void make_set(int k) {
    parent[k] = k;
    level[k] = 1;
}

int find_set(int k) {
    if (parent[k] == k)
        return k;
    return parent[k] = find_set(parent[k]);
}

void union_sets(int a, int b) {
    int x = find_set(a);
    int y = find_set(b);
    if (x != y) {
        if (level[x] < level[y])
            swap(x, y);
        parent[y] = x;
        if (level[x] == level[y])
            level[x]++;
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        make_set(i);
    for (int i = 1; i <= m; i++) {
        cin >> key >> x >> y;
        if (key == 2)
            if (find_set(x) == find_set(y))
                cout << "DA\n";
            else
                cout << "NU\n";
        else
            union_sets(x, y);
    }
}