Cod sursa(job #403581)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 25 februarie 2010 09:12:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <algorithm>
using namespace std;

#define DIM 1<<17

int N, M;
int r[ DIM], t[ DIM ];

inline void unite( const int &x, const int &y ) {

    if( r[ x ] < r[ y ] )
        t[ x ] = y;
    else
        t[ y ] = x;

    if( r[ x ] == r[ y ] )
        ++r[ x ];
}

inline int find( const int &x ) {

    if( x != t[ x ] )
        t[ x ] = find( t[ x ] );

    return t[ x ];
}

int main() {

    freopen( "disjoint.in", "r", stdin );
    freopen( "disjoint.out", "w", stdout );

    int i, x, y, tip;

    scanf( "%d %d", &N, &M );

    for( i = 1; i <= N; ++i )
        t[ i ] = i;

    while( M-- ) {

        scanf( "%d %d %d", &tip, &x, &y );

        if( tip == 1 )
            unite( find( x ), find( y ) );
        else if( tip == 2 )
            if( find( x ) == find( y ) )
                printf( "DA\n" );
            else
                printf( "NU\n" );
    }

    return 0;
}