Cod sursa(job #1989070)

Utilizator hanganflorinHangan Florin hanganflorin Data 5 iunie 2017 18:49:28
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
using namespace std;

ifstream is("disjoint.in");
ofstream os("disjoint.out");

int n, m, a[100002], rang[100002];
void SetRoots();
int GetRoot(int x);
void Merge(int x, int y);

int main()
{
    is >> n >> m;
    SetRoots();
    for ( int i = 0, cod, x, y; i < m; ++i )
    {
        is >> cod >> x >> y;
        if ( cod == 1 )
            Merge(x, y);
        else
        {
            if ( GetRoot(x) == GetRoot(y) )
                os << "DA\n";
            else
                os << "NU\n";
        }
    }
    is.close();
    os.close();
    return 0;
}
void SetRoots()
{
    for ( int i = 1; i < n; ++i )
    {
        a[i] = i;
        rang[i] = 1;
    }
}
int GetRoot(int x)
{
    if ( a[x] == x )
        return x;
    int f = GetRoot(a[x]);
    a[x] = f;
    return f;
}
void Merge(int x, int y)
{
    x = GetRoot(x);
    y = GetRoot(y);
    if ( rang[x] < rang[y] ) // daca rangu lui x e mai mic modific radacina lu x
        a[x] = y;
    else
        a[y] = x;
    if ( rang[x] == rang[y] ) // cresc rangu noii multimi
        rang[y]++;
}