Cod sursa(job #1823106)

Utilizator dorumusuroiFMI - Doru Musuroi dorumusuroi Data 5 decembrie 2016 22:17:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <fstream>
using namespace std;

#define cin f
#define cout g

class Nod{
public:
    Nod* parinte;
    int rang;
    Nod();
    Nod* find();
    void unite(Nod* nod);
};
Nod::Nod(){
    this->parinte = this;
    this->rang = 0;
}

Nod* Nod::find(){
    if(this != parinte){
        this->parinte = parinte->find();
    }
    return this->parinte;
}

void Nod::unite(Nod* nod){
    Nod *parinte1 = this->find(),
         *parinte2 = nod->find();
    if(parinte1 -> rang > parinte2 -> rang){
        parinte2->parinte = parinte1;
    }
    else if(parinte1->rang < parinte2->rang){
        parinte1->parinte = parinte2;
    }
    else{
        parinte1->parinte = parinte2;
        parinte2->rang++;
    }
}


int main()
{
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    int n, m;
    cin >> n >> m;
    Nod** noduri = new Nod*[n+1];
    for(int i = 1; i <= n; ++i){
        noduri[i] = new Nod();
    }

    for(int i = 0; i < m; ++i){
        int c, x, y;
        cin >> c >> x >> y;
        if(c == 1){
            noduri[x]->unite(noduri[y]);
        }
        else{
            if(noduri[x]->find()==noduri[y]->find()){
                cout << "DA" << '\n';
            }
            else{
                cout << "NU" << '\n';
            }
        }
    }
    for(int i = 0; i < n; ++i){
        delete noduri[i];
    }
    return 0;
}