Cod sursa(job #3193349)

Utilizator AnSeDraAndrei Sebastian Dragulescu AnSeDra Data 14 ianuarie 2024 14:50:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>

using namespace std;

const int Nmax = 100005;

int n, m;

struct element{
    int root;
    int depth;
};

element padure[Nmax];

void preinit(){
    for(int i = 1; i <= n; i++){
        padure[i].root = -1;
        padure[i].depth = 1;
    }
}

int Find_Root(int nod){
    if(padure[nod].root < 0){
        return nod;
    }

    int root = Find_Root(padure[nod].root);
    padure[nod].root = root;
    return root;
}

void Union(int x, int y){
    int r_x, r_y;

    r_x = Find_Root(x);
    r_y = Find_Root(y);

    if(r_x == r_y){
        return;
    }

    if(padure[r_x].depth > padure[r_y].depth){
        swap(r_x, r_y);
    }

    padure[r_y].depth += padure[r_x].depth;
    padure[r_x].root = r_y;
}

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

    int type, a, b;

    fin >> n >> m;

    preinit();

    for(int i = 1; i <= m; i++){
        fin >> type >> a >> b;

        if(type == 1){
            Union(a, b);
        }
        else{
            if(Find_Root(a) == Find_Root(b)){
                fout << "DA" << '\n';
            }
            else{
                fout << "NU" << '\n';
            }
        }
    }
    return 0;
}