Cod sursa(job #2942912)

Utilizator VladWero08Olaeriu Vlad Mihai VladWero08 Data 20 noiembrie 2022 12:29:06
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>

using namespace std;

int NrNodes;
int Fathers[100020], Heights[100020];

int Find(int Node) {
    if(Fathers[Node] == 0)
        return Node;
    Fathers[Node] = Find(Fathers[Node]);
    return Fathers[Node];
}

void Union(int NodeX, int NodeY) {
    if(Heights[NodeX] > Heights[NodeY]){
        Fathers[NodeY] = NodeX;
    } else{
        Fathers[NodeX] = NodeY;
    }

    if(Heights[NodeX] == Heights[NodeY])
        Heights[NodeX]++;
}

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

    fin >> NrNodes;
    for(int i = 1; i <= NrNodes; i++){
        Fathers[i] = 0;
        Heights[i] = 1;
    }

    int M;
    fin  >> M;
    for(int i = 0; i < M; i++){
        int cod, X, Y;
        fin >> cod >> X >> Y;

        int fatherX = Find(X), fatherY = Find(Y);
        if(cod == 1){
            Union(fatherX,fatherY);
        } else{
            if( fatherX== fatherY)
                fout << "DA" << endl;
            else
                fout << "NU" << endl;
        }
    }

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