Cod sursa(job #2837335)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 22 ianuarie 2022 09:54:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb

#include <fstream>

#define MAX 100005
using namespace std;

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

int Arbore[MAX], Rank[MAX];

int findR(int val){
    int r = val, y;
    while(Arbore[r] != r)
        r = Arbore[r];

    while(Arbore[val] != val){
        y = Arbore[val];
        Arbore[val] = r;
        val = y;
    }
    return r;
}

void Union(int Rx, int Ry){
    if(Rank[Rx] > Rank[Ry])
        Arbore[Rx] = Ry;
    else Arbore[Ry] = Rx;

    if(Rank[Rx] == Rank[Ry])
        Rank[Ry]++;
}

int main()
{
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; ++i)
    {
        Arbore[i] = i;
        Rank[i] = 1;
    }

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

        if(c == 1){
            Union(findR(x), findR(y));
        }
        else {
            if(findR(x) == findR(y))
                fout << "DA\n";
            else fout << "NU\n";
        }
    }
    return 0;
}