Cod sursa(job #2824231)

Utilizator Avram_RobertAvram Robert Ionut Avram_Robert Data 31 decembrie 2021 16:34:59
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>

using namespace std;

const int NMAX = 100000;

int tata[1 + NMAX];

int gasit(int a)
{
    if (tata[a] != a)
    {
        return gasit(tata[a]);
    }
    else
    {
        return a;
    }
}
void uneste(int a,int b)
{
    int x = gasit(a);
    int y = gasit(b);
    if (x == y)
    {
        return;
    }
    else
    {
        tata[y] = x;
    }
}

int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");
    int n, m;
    in >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        tata[i] = i;
    }
    for (int i = 1; i <= m; i++)
    {
        int tipOperatie, a, b;
        in >> tipOperatie >> a >> b;
        if (tipOperatie == 2)
        {
            a = gasit(a);
            b = gasit(b);
            if (a == b)
            {
                out << "DA" <<'\n';
            }
            else
                out << "NU" << '\n';
        }
        else
        {
            uneste(a, b);
        }
    }
    for (int i = 1; i <= n; i++)
    {
        out << tata[i] << ' ';
    }
}