Cod sursa(job #3167813)

Utilizator christalknightChristian Micea christalknight Data 11 noiembrie 2023 09:45:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int nmax = 100003;
int n, m;
int tata[nmax];
int rang[nmax];

void readAndSolve(void);
void unite(int x, int y);
int root(int x);

int main(){
    int i;
    
    readAndSolve();
    }

void readAndSolve(void){
    int a, x, y;
    
    fin>>m>>m;

    while(m--){
        fin>>a>>x>>y;

        if(a == 1)
            unite(x, y);
        else if(a == 2){
            if(root(x) != root(y))
                fout<<"NU\n";
            else fout<<"DA\n";
            }
        }
    }

void unite(int x, int y){
    int rootx, rooty;

    rootx = root(x);
    rooty = root(y);

    if(rootx != rooty){
        if(rang[rootx] == rang[rooty]){
            tata[rootx] = rooty;
            rang[rootx]++;
            }
        else if(rang[rootx] > rang[rooty])
            tata[rootx] = rooty;
        else tata[rooty] = rootx;
        }
    }

int root(int x){
    int radacina;

    if(!tata[x])
        return x;
    else{
        radacina = root(tata[x]);
        tata[x] = radacina;
        return radacina;
        }
    }