Cod sursa(job #2942984)

Utilizator ctimburCristina T ctimbur Data 20 noiembrie 2022 13:55:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
using namespace std;

const int NMAX = 100001;

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

int tata[NMAX], rang[NMAX];

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

void unite(int x, int y) {
    // Cautam radacinile ca sa unim cele doua grafuri
    // Radacina grafului cu rangul mai mic va deveni root celui cu rang mai mare
    int root_x = find(x);
    int root_y = find(y);
    if (root_x == root_y)
        return;

    if (rang[root_x] > rang[root_y]) {
        tata[root_y] = root_x;
        rang[root_x] += rang[root_y];
    }
    else {
        tata[root_x] = root_y;
        rang[root_y] += rang[root_x];
    }
}

int main() {
    int n, m, op, x, y;

    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        tata[i] = i;
        rang[i] = 1;
    }

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