Cod sursa(job #3321427)

Utilizator alexiabortunBortun Alexia alexiabortun Data 9 noiembrie 2025 14:20:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
#define N 100005
int n, m, R[N], rang[N];
int gasit(int x)
{
    int r, y;
    ///merg in sus pe arbore pana gasesc o nod care este singur in multime
    for(r = x; R[r] != r; r = R[r]);

    ///compresia drumului = unim toate nodurile la radacina
    while(R[x] != x)
    {
        y = R[x];
        R[x] = r;
        x = y;
    }
    return r;
}

void uneste(int x, int y)
{
    ///unesc arborele cu inaltimea mai mica de cel cu inaltimea mai mare
    if(rang[x] < rang[y])
        R[y] = x;
    else R[x] = y;
    if(rang[x] == rang[y])
        rang[y]++;
}
int main()
{
    fin >> n >> m;
    int op, x, y;
    for(int i = 1; i <= n; i++)
    {
        R[i] = i;
        rang[i] = 1;
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> op >> x >> y;
        if(op == 2)
            if(gasit(x) == gasit(y))
                fout << "DA\n";
            else fout << "NU\n";
        else if(gasit(x) != gasit(y))
            uneste(gasit(x), gasit(y));
    }
    return 0;
}