Cod sursa(job #2935993)

Utilizator madalin1902Florea Madalin Alexandru madalin1902 Data 7 noiembrie 2022 19:49:08
Problema Paduri de multimi disjuncte Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, cod, x, y;

vector <int> tata;
vector <int> nivel;


int radacina(int nod) {
    while (tata[nod])
        nod = tata[nod];

    return nod;
}


void uneste(int x, int y) {
    if (nivel[x] == nivel[y]) {
        tata[y] = radacina(x);
        ++nivel[y];
    }
    else if (nivel[x] > nivel[y])
        tata[y] = radacina(x);
    else
        tata[x] = radacina(y);
}


int main() {
    fin >> n >> m;

    tata.resize(n + 1);
    nivel.resize(n + 1);

    for (int i = 1; i <= m; ++i) {
        fin >> cod >> x >> y;

        if (cod == 1) {
            uneste(x, y);
        }
        else {
            if (radacina(x) == radacina(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    fin.close();
    fout.close();
    return 0;
}