Cod sursa(job #2659544)

Utilizator Florinos123Gaina Florin Florinos123 Data 16 octombrie 2020 23:45:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>

using namespace std;

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

int n, m;

int tata[100005];

int lg[100005];

int Radacina (int nod)
{
    if (tata[nod] == 0)
        return nod;
    return Radacina(tata[nod]);
}

void Uneste (int x, int y)
{
    int x_parent = Radacina(x);
    int y_parent = Radacina(y);

    if (lg[x_parent] >= lg[y_parent])
    {
        while (tata[y])
        {
            int aux = tata[y];
            tata[y] = x_parent;
            y = aux;
        }

        lg[x_parent] += lg[y_parent];
        tata[y_parent] = x_parent;
    }
    else
    {
        while (tata[x])
        {
            int aux = tata[x];
            tata[x] = y_parent;
            x = aux;
        }

        lg[y_parent] += lg[x_parent];
        tata[x_parent] = y_parent;
    }
}

int main()
{
    f >> n >> m;

    for (int i=1; i<=n; i++)
        lg[i] = 1;

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

        if (type == 1)
            Uneste(x, y);
        else if (type == 2)
        {
            if (Radacina(x) == Radacina(y))
                g << "DA" << "\n";
            else g << "NU" << "\n";
        }
    }

    return 0;
}