Cod sursa(job #2868001)

Utilizator ionutpop118Pop Ioan Cristian ionutpop118 Data 10 martie 2022 18:02:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <vector>

using namespace std;
const int NMAX = 100000;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int t[NMAX + 5], h[NMAX + 5];

int boss(int x) {
    while (x != t[x]) {
        x = t[x];
    }
    return x;
}

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

    if (x == y) {
        return ;
    }

    if (h[x] < h[y]) {
        t[x] = y;
    } else if (h[x] > h[y]) {
        t[y] = x;
    } else {
        t[x] = y;
        ++h[y];
    }
}

bool solve(int x, int y) {
    return boss(x) == boss(y);
}

int main()
{
    int n, k, q, x, y;
    fin >> n >> k;
    for (int i = 1; i <= n; ++i) {
        t[i] = i;
    }

    for (int i = 1; i <= k; ++i) {
        fin >> q >> x >> y;
        if (q == 1) {
            unite(x, y);
        } else {
            if (solve(x, y)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}