Cod sursa(job #3273526)

Utilizator vladm98Munteanu Vlad vladm98 Data 2 februarie 2025 15:50:27
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

using namespace std;

int tata[100005], height[100005];

void reset(int n) {
    for (int i = 1; i <= n; i++) {
        tata[i] = i;
        height[i] = 1;
    }
}

int getRoot(int x) {
    int root = x;
    while (root != tata[root]) {
        root = tata[root];
    }
    // compresia drumurilor
    while (x != root) {
        int tx = tata[x];
        tata[x] = root;
        x = tx;
    }
    return root;
}

void unite(int x, int y) {
    x = getRoot(x);
    y = getRoot(y);

    if (height[x] < height[y]) {
        tata[x] = y;
    } else if (height[x] > height[y]) {
        tata[y] = x;
    } else { // egalitate
        tata[y] = x;
        height[x] += 1;
    }

    tata[y] = x;
}

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

    int n, m;
    cin >> n >> m;
    reset(n);

    for (int i = 1; i <= m; i++) {
        int op, x, y;
        cin >> op >> x >> y;

        if (op == 2) {
            if (getRoot(x) == getRoot(y)) {
                cout << "DA" << '\n';
            } else {
                cout << "NU" << '\n';
            }
        } else {
            unite(x, y);
        }
    }
    return 0;
}