Cod sursa(job #2983187)

Utilizator tusortudor neagu tusor Data 21 februarie 2023 19:38:14
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <fstream>

using namespace std;
#define NMAX 100020
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int T[NMAX], RG[NMAX];
int N, M;

bool query(int x, int y)
{
    // x si y sunt in acelasi arbore daca au aceeasi radacina
    return get_root(x) == get_root(y);
}
int get_root(int node)
{
    int aux = node;
    while (T[node] > 0)
        node = T[node];
    int root = node;
    // mai parcurg odata acelasi drum si unesc nodurile de root
    node = aux;
    while (node != root)
    {
        aux = T[node];
        T[node] = root;
        node = aux;
    }
    return root;
}

void join(int x, int y)
{
    int root_x = get_root(x); // radacina arborelui lui x
    int root_y = get_root(y); // radacina arborelui lui y
    if (root_x == root_y)     // sunt deja in acelasi arbore
        return;
    if (T[root_x] <= T[root_y])
    { // arborele lui x are mai multe noduri
        T[root_x] += T[root_y];
        T[root_y] = root_x; // legam arborele lui y de arborele lui x
    }
    else
    {
        T[root_y] += T[root_x];
        T[root_x] = root_y; // legam arborele lui x de arborele lui y
    }
}

int main()
{

    int i, x, y, cd;
    cin >> N >> M;
    // initial fiecare nod pointeaza catre el insusi iar rangul fiecarui arbore este 1
    for (i = 1; i <= N; i++)
    {
        T[i] = i;
        RG[i] = 1;
    }

    for (i = 1; i <= M; i++)
    {
        cin >> cd >> x >> y;

        if (cd == 2)
        {
            // verific daca radacina arborilor in care se afla x respectiv y este egala
            if (query(x, y))
                cout << "DA"
                     << "\n";
            else
                cout << "NU"
                     << "\n";
        }
        else // unesc radacinile arborilor corespunzatori multimilor nodurilor x respectiv y
        {
            if (get_root(x) == get_root(y))
            {

                return 0;
            }
            join(get_root(x), get_root(y));
        }
    }

    return 0;
}