Cod sursa(job #2983193)

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


using namespace std;
ifstream cin("");
ofstream cout("");
int t[501], rang[501];

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;
}

int querry(int x, int y)
{
    return get_root(x) == get_root(y);
}
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 n, m, i, op, x, y, k = 1;
    cin >> n >> m;
    for (i = 1; i <= m; ++i)
    {
        cin >> op >> x >> y;
        if (op == 1)
            join(x, y);
        else
        {
            if (querry(x, y))
                cout << "DA" << '\n';
            else
                cout << "NU" << '\n';
        }
    }
    return 0;
}