Cod sursa(job #1989062)

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

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

int n, m, a[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;
}
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);
    a[x] = y;
}