Cod sursa(job #2979886)

Utilizator RobertlelRobert Robertlel Data 16 februarie 2023 08:20:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f ("disjoint.in");
ofstream g ("disjoint.out");

int t[100005] , rang[100005] , x , y , n , m , a;

int radacina (int a)
{
    if (t[a] == 0)
        return a;
    else
    {
        int k = radacina (t[a]);
        t[a] = k;
        return k;
    }
}

void unire (int a , int b)
{
    int rx = radacina (a) , ry = radacina (b);
    if (rx != ry)
    {
        if (rang[rx] < rang[ry])
            t[rx] = ry;
        else
            if (rang[ry] < rang[rx])
            t[ry] = rx;
        else
            t[ry] = rx , rang[rx]++;
    }
}

int main()
{
    f >> n >> m;
    for (int i = 1 ; i <= m ; i++)
    {
        f >> a >> x >> y;
        if (a == 1)
        {
            unire (x , y);
        }
        else
            if (radacina (x) == radacina (y))
            g << "DA" << '\n';
        else
            g << "NU" << '\n';
    }
    return 0;
}