Cod sursa(job #3218472)

Utilizator hutanuHutanu Andrei hutanu Data 27 martie 2024 11:41:16
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#define NMAX 100002

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int n, m, tata[NMAX];
int h[NMAX];

void Union(int x, int y)
{
    if(h[x] < h[y])
        tata[x] = y;
    else
    {
        if(h[y] < h[x])
            tata[y] = x;
        else
        {
            tata[y] = x;
            h[y]++;
        }
    }
}

int Find(int x)
{   int r, y;
    ///mai intai aflu radacina arborelui din care face parte x
    r = x;
    while(tata[r])
        r = tata[r];
    return r;
    /*
    ///parcurg din nou drumul de la x la r si fac toate nodurile fii ai lui x
    do
    {
        y = tata[x];
        tata[x] = r;
        x = y;
    }
    while(tata[x] != r);
    */
}

int main()
{
    int operatie, x, y, i;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> operatie;
        if(operatie == 1)
        {
            fin >> x >> y;
            Union(x, y);
        }
        else
        {
            fin >> x >> y;
            if(Find(x) != Find(y))
                fout << "NU" << '\n';
            else
                fout << "DA" << '\n';
        }
    }
    return 0;
}