Cod sursa(job #3134997)

Utilizator AndreiN96Andrei Nicula AndreiN96 Data 1 iunie 2023 12:30:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>

using namespace std;

const int N = 100000;
int t[N + 1],  nr[N + 1];

int rad(int x)
{
    if (t[x] == 0)
    {
        return x;
    }
    t[x] = rad(t[x]);
    return t[x];
}
void reuniune(int x, int y)
{
    int rx = rad(x);
    int ry = rad(y);
    if (nr[rx] > nr[ry])
    {
        t[ry] = rx;
        nr[rx] += nr[ry];
    }
    else
    {
        t[rx] = ry;
        nr[ry] += nr[rx];
    }
}
int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    int n, m;
    in >> n >> m;
    for (int i = 1; i <= n; i ++)
    {
        nr[i] = 1;
    }
    for (int i = 0; i < m; i ++)
    {
        int cod, x, y;
        in >> cod >> x >> y;
        if (cod == 1)
        {
            reuniune(x, y);
        }
        else
        {
            if (rad(x) == rad(y))
            {
                out << "DA\n";
            }
            else
            {
                out << "NU\n";
            }
        }
    }

    in.close();
    out.close();

    return 0;
}