Cod sursa(job #3206820)

Utilizator ionutpop118Pop Ioan Cristian ionutpop118 Data 24 februarie 2024 11:13:26
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>

using namespace std;

const int NMAX = 100000;

int father[NMAX + 1];
int depth[NMAX + 1];

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

int root(int x) {
    while (x != father[x]) 
        x = father[x];
    return x;
}

void unite(int a, int b) {
    int x = root(a);
    int y = root(b);

    if (x == y) {
        return;
    }

    if (depth[x] > depth[y])
        father[x] = y;
    else if (depth[x] < depth[y])
        father[y] = x;
    else {
        father[x] = y;
        depth[x]++;
    }
}

bool query(int a, int b) {
    int x = root(a);
    int y = root(b);

    return x == y;
}

int main() {
    int n, t, x, y, q;

    fin >> n >> q;

    for (int i = 1; i <= n; i++) {
        father[i] = i;
        depth[i] = 1;
    }

    for (int i = 1; i <= q; i++) {
        fin >> t >> x >> y;
        if (t == 1) { // Unite nodes x and y
            unite(x, y);
        } else {
            if (query(x, y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}