Cod sursa(job #2942868)

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

using namespace std;

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

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

void UnionFind::Read(){
    ifstream fin("disjoint.in");
    fin >> NrNodes;
    for(int i = 0; i <= NrNodes; i++){
        Init();
    }
    fin.close();
}

void UnionFind::Init() {
    Heights.push_back(0);
    Fathers.push_back(0);
    UnionSize.push_back(1);
}

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

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

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

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

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

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

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

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