Cod sursa(job #1809823)

Utilizator ChelaruPaulChelaru Paul ChelaruPaul Data 19 noiembrie 2016 12:24:25
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int r[ 100001 ] , t[ 100001 ] ;

int findd ( int  x )
{
    int rad = x ;

    while( t[ rad ] != 0 )
        rad = t[ rad ] ;

    int tmp ;

    while( t[ x ] != 0 )
    {
        tmp = t[ x ] ;
        t[ x ] = tmp ;
        x = rad ;
    }

    return rad ;
}

void uniune( int x , int y )
{

    if( r[ x ] > r[ y ] )
        t[ y ] = x ;
    else
        if( r[ x ] < r [ y ] )
            t[ x ] = y ;
        else
        {
            t[ y ] = x ;
            r[ x ] ++;
        }
}

int main()
{
    int N , M , q , x , y , i ;
    in >> N >> M ;

    for( i = 1 ; i <= M ; i ++)
    {
        in >> q >> x >> y ;

        if( q == 1 )
            uniune( x ,  y ) ;
        else
            if( findd( x ) == findd( y ) )
                out << "DA" << '\n' ;
            else
                out << "NU" << '\n' ;
    }
    return 0;
}