Cod sursa(job #3200263)

Utilizator misu_LIXulescu Vasile misu_L Data 4 februarie 2024 07:20:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

int n, m, c, a, b, tata[100005], lg[100005];

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

int fnd(int x) {
    int cpy = x;
    while (cpy != tata[cpy]) {
        cpy = tata[cpy];
    }

    while (x != cpy) {
        tata[x] = cpy;
        x = tata[x];
    }
    return cpy;
}

void unite(int a, int b) {
    int x = fnd(a), y = fnd(b);
    if (x == y) return ;

    if (lg[x] < lg[y]) {
        tata[x] = tata[y];
        lg[y] += lg[x];
    } else {
        tata[y] = tata[x];
        lg[x] += lg[y];
    }
}

int main()
{
    cin >> n >> m;
    make_set();

    while (m--) {
        cin >> c >> a >> b;
        if (c == 1) {
            unite(a, b);
        } else {
            if (fnd(a) == fnd(b))
                cout << "DA" << '\n';
            else
                cout << "NU" << '\n';
        }
    }
    return 0;
}