Cod sursa(job #1820974)

Utilizator horatiucheval2Horatiu Andrei Cheval horatiucheval2 Data 2 decembrie 2016 13:45:36
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
using namespace std;

const int MAX = 100000;

struct Node{
    int value;
    int parent;
};
Node sets[MAX];

int getRoot(int x){
    if(sets[x].parent == -1){
        return x;
    }else{
        return getRoot(sets[x].parent);
    }
}


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

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; i++){
        sets[i].value = i;
        sets[i].parent = -1;
    }

    for(int i = 1; i <= m; i++){
        int op, x, y;
        fin >> op >> x >> y;

        if(op == 1){
            int rx = getRoot(x);
            int ry = getRoot(y);
            sets[min(rx, ry)].parent = max(rx, ry);
        }else if(op == 2){
            int rx = getRoot(x);
            int ry = getRoot(y);
            ///
            int temp;

            while(sets[x].parent != -1){
                temp = x;
                x = sets[x].parent;
                sets[temp].parent = rx;
            }


            while(sets[y].parent != -1){
                temp = y;
                y = sets[y].parent;
                sets[temp].parent = ry;
            }

            ///
            if(rx == ry){
                fout << "DA\n";
            }else{
                fout << "NU\n";
            }
        }
    }


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