Cod sursa(job #3359108)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 24 iunie 2026 16:17:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
/*
https://infoarena.ro/problema/disjoint
*/
#include <fstream>
#include <vector>

using namespace std;

vector <int> t;
vector <int> nr;

int radacina(int x)
{
    if (t[x] == 0)
    {
        return x;
    }
    t[x] = radacina(t[x]);
    return t[x];
}

void reuniune(int x, int y)
{
    int rx = radacina(x);
    int ry = radacina(y);
    if (nr[rx] < nr[ry])
    {
        t[rx] = ry;
        nr[ry] += nr[rx];
    }
    else
    {
        t[ry] = rx;
        nr[rx] += nr[ry];
    }
}

bool verif(int x, int y)
{
    return (radacina(x) == radacina(y));
}

int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");
    int n, q;
    in >> n >> q;
    t.resize(n + 1, 0);
    nr.resize(n + 1, 1);
    for (int i = 0; i < q; i++)
    {
        int tip, x, y;
        in >> tip >> x >> y;
        if (tip == 1)
        {
            reuniune(x, y);
        }
        else
        {
            if (verif(x, y))
            {
                out << "DA\n";
            }
            else
            {
                out << "NU\n";
            }
        }
    }
    in.close();
    out.close();
    return 0;
}