Cod sursa(job #2605886)

Utilizator bmc213Mihai Cosmin bmc213 Data 26 aprilie 2020 10:29:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

int tata[100001], rang[100001], n, m, i, x, y, t;

int tata_multime( int nod )
{
    if( tata[nod] != nod )
        tata[nod] = tata_multime( tata[nod] );
    return tata[nod];
}

void Union( int px, int py )
{
    px = tata_multime( px );
    py = tata_multime( py );
    if( px != py )
    {
        if( rang[px] < rang[py] )
        {
            rang[py] += rang[px];
            tata[px] = py;
        }
        else
        {
            rang[px] += rang[py];
            tata[py] = px;
        }
    }
}
int main()
{
    f >> n >> m;
    for( i = 1; i <= n; ++ i )
    {
        tata[i] = i;
        rang[i] = 1;
    }
    for( ; m; m -- )
    {
        f >> t >> x >> y;
        if( t == 1 )
        {
            Union( x, y );
        }
        else
        {
            if( tata_multime(x) == tata_multime(y) )
                g << "DA" << "\n";
            else
                g << "NU" << "\n";
        }
    }
    return 0;
}