Cod sursa(job #1621763)

Utilizator felipeGFilipGherman felipeG Data 29 februarie 2016 21:28:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
#include <iostream>
#define Nmax 100000
using namespace std;

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

int n, m, t[ Nmax ], h[ Nmax ];

void init ()
{
    for ( int i = 1; i <= n; ++ i )
    {
        t[ i ] = i;
        h[ i ] = 1;
    }
}

int multime ( int x )
{
    if ( t[ x ] == x )
        return x;

    t[ x ] = multime( t[ x ] );
    return t[ x ];
}

void unificare ( int a, int b )
{
    a = multime ( a );
    b = multime ( b );

    if ( h[ b ] > h[ a ] )
        t[ a ] = b;
    else
        t[ b ] = a;

    if ( h[ a ] == h[ b ] )
        h[ a ] ++;
}

int main ()
{
    int x, y, op;

    f >> n >> m;

    init ();

    for ( int i = 1; i <= m; ++ i )
    {
        f >> op >> x >> y;

        if ( op == 1 )
            unificare ( x, y );
        else
        {
            if ( multime( x ) == multime ( y ) )
                g << "DA\n";
            else
                g << "NU\n";
        }
    }
    return 0;
}