Cod sursa(job #2944148)

Utilizator alexdn6Dina Alexandru alexdn6 Data 22 noiembrie 2022 09:09:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f ("disjoint.in");
ofstream g ("disjoint.out");
int n, nr_op;
vector<int> tata(100000, 0), h(100000, 0);

int Reprez(int u) {
    while(tata[u]!=0)
        u=tata[u];
    return u;
}

void Reuneste(int u, int v) {
    int ru = Reprez(u);
    int rv = Reprez(v);
    if (h[ru] > h[rv])
        tata[rv] = ru;
    else {
        tata[ru] = rv;
        if(h[ru] == h[rv])
            h[rv] = h[rv]+1;
    }
}

int main() {
    f >> n >> nr_op;
    h.resize(n + 1);
    tata.resize(n + 1);
    int x, y, cod;
    for(int i  = 0; i < nr_op; i++) {
        f >> cod >> x >> y;
        if (cod == 1) {
            Reuneste(Reprez(x), Reprez(y));
        }
        else {
            if(Reprez(x) == Reprez(y))
                g << "DA\n";
            else
                g << "NU\n";
        }
    }
    return 0;
}