Cod sursa(job #2012900)

Utilizator HumikoPostu Alexandru Humiko Data 19 august 2017 19:52:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>

using namespace std;

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

int tata[100001], h[100001];

int rege ( int x )
{
    int c_x = x;
    while ( x != tata[x] )
        x = tata[x];
    while ( c_x != x )
    {
        int c_c_x = c_x;
        c_x = tata[c_x];
        tata[c_c_x] = x;
    }
    return x;
}

void unire ( int a, int b )
{
    int st1 = rege(a);
    int st2 = rege(b);
    if ( st1 == st2 )
        return;
    if ( h[st1] > h[st2] )
        tata[st2] = st1;
    else
    {
        tata[st1] = st2;
        if ( h[st1] == h[st2] )
            h[st2]++;
    }
}
int main()
{
    int m, n, cod, x, y;
    fin>>n>>m;
    for ( int i = 1; i <= n; ++i )
    {
        tata[i] = i;
        h[i] = 1;
    }
    for ( int i = 1; i <= m; ++i )
    {
        fin>>cod>>x>>y;
        if ( cod == 1)
            unire(x, y);
        else
        {
            if ( rege(x) == rege(y) )
                fout<<"DA"<<'\n';
            else
                fout<<"NU"<<'\n';
        }
    }
}