Cod sursa(job #3208121)

Utilizator BoggiGurau Bogdan Boggi Data 27 februarie 2024 20:12:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>
using namespace std;

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

#define VI vector<int>

VI tata, rankg;
int n, m;

int findRoot(int node) {
    if (tata[node] == 0) {
        return node;
    }

    int x = findRoot(tata[node]);
    tata[node] = x;
    return x;
}

void integrate(int nodeX, int nodeY) {
    int subArbX = findRoot(nodeX),
        subArbY = findRoot(nodeY);
    
    if (subArbX == subArbY) {
        return;
    }

    if (rankg[subArbX] < rankg[subArbY]) {
        tata[subArbX] = subArbY;
    } else if (rankg[subArbX] == rankg[subArbY]) {
        tata[subArbY] = subArbX;
        ++rankg[subArbX];
    } else {
        tata[subArbY] = subArbX;
    }
}

void printTati() {
    for (int i = 1; i < tata.size(); ++i) {
        fout << tata[i] << ' ';
    }
    fout << '\n';
    for (int i = 1; i <= n; ++i) {
        fout << i << ' ';
    }
    fout << '\n';
}

int main() {
    fin >> n >> m;
    rankg = tata = VI(n + 1, 0);
    for (int i = 0; i < m; ++i) {
        //printTati(), fout << '\n';
        int opType, x, y;
        fin >> opType >> x >> y;
        if (opType == 2) {
            if (findRoot(x) == findRoot(y)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        } else {
            integrate(x, y);
        }
    }
}