Cod sursa(job #2246349)

Utilizator pinteastefanPintea Teodor Stefan pinteastefan Data 26 septembrie 2018 23:07:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;

int arbore[100001], dimensiune[100001];

void initializare(int noduri){
    for (int i = 1; i <= noduri; i++){
        arbore[i] = i;
        dimensiune[i] = 1;
    }
}

int reuniuneaDupaRang(int nod){
    if (nod != arbore[nod]){
      arbore[nod] = reuniuneaDupaRang(arbore[nod]);
    }
    return arbore[nod];
}

void compresiaDrumurilor(int nod1, int nod2 ){
    nod1 = reuniuneaDupaRang(nod1);
    nod2 = reuniuneaDupaRang(nod2);

    if(dimensiune[nod1] < dimensiune[nod2]){
        dimensiune[nod2] += dimensiune[nod1];
        arbore[nod1] = nod2;
    }
    else{
        dimensiune[nod1] += dimensiune[nod2];
        arbore[nod2] = nod1;
    }
}
int main() {
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    int n , m;
    f >> n >> m;
    initializare(n);
    for (int i = 1; i <= m; i++){
        int cod, x, y;
        f >> cod >> x >> y;
        if(cod == 1){
            compresiaDrumurilor(x ,y);
        }
        else{
            if(reuniuneaDupaRang(x) == reuniuneaDupaRang(y)){
                g << "DA" << "\n";
            }
            else{
                g << "NU" << "\n";
            }
        }
    }
    return 0;
}