Cod sursa(job #2890443)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 15 aprilie 2022 16:40:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>

using namespace std;

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

const int max_size = 1e5 + 1;

int father[max_size], rang[max_size];

int caut (int x)
{
    int aux = x, y;
    while (aux != father[aux])
    {
        aux = father[aux];
    }
    while (x != father[x])
    {
        y = father[x];
        father[x] = aux;
        x = y;
    }
    return aux;
}

void unite (int x, int y)
{
    if (rang[x] > rang[y])
    {
        father[y] = x;
    }
    else
    {
        father[x] = y;
    }
    if (rang[x] == rang[y])
    {
        rang[y]++;
    }
}

int main ()
{
    int n, t;
    in >> n >> t;
    for (int i = 1; i <= n; i++)
    {
        father[i] = i;
        rang[i] = 1;
    }
    while (t--)
    {
        int op, x, y;
        in >> op >> x >> y;
        if (op == 1)
        {
            unite(caut(x), caut(y));
        }
        else
        {
            if (caut(x) == caut(y))
            {
                out << "DA";
            }
            else
            {
                out << "NU";
            }
            out << '\n';
        }
    }
}