Cod sursa(job #2824239)

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

using namespace std;

const int NMAX = 100000;

pair<int, int>tata[1 + NMAX];

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

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] = make_pair(i, 1);
    }
    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);
        }
    }
}