Cod sursa(job #2944994)

Utilizator VladWero08Olaeriu Vlad Mihai VladWero08 Data 23 noiembrie 2022 11:35:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

class UnionFind{
    int NrNodes;
    int cod, X, Y;
    vector<int> Heights, Fathers;
public:
    // Exclusiv pentru problema
    void Solve();

    // Functii union find
    void Init();
    int Find(int);
    void Union(int,int);
};

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

void UnionFind::Union(int NodeX, int NodeY) {
    int RootX = Find(NodeX), RootY = Find(NodeY);

    if(Heights[RootX] < Heights[RootY]){
        Fathers[RootX] = RootY;
    }
    else if(Heights[RootX] > Heights[RootY]){
        Fathers[RootY] = RootX;
    } else{
        Fathers[RootY] = RootX;
        Heights[RootX]++;
    }
}

void UnionFind::Solve() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    fin >> NrNodes;
    Heights.resize(NrNodes + 1);
    Fathers.resize(NrNodes + 1);

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

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

        if(cod == 1){
            Union(X,Y);
        } else{
            if( Find(X) == Find(Y))
                fout << "DA" << "\n";
            else
                fout << "NU" << "\n";
        }
    }

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

int main() {
    UnionFind multime;
    multime.Solve();
    return 0;
}