Cod sursa(job #403589)

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

#define DIM 1<<17
#define MAX 1<<15

char s[ MAX ];
int N, M;
int cnt, 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 ];
}

inline void read( int &val ) {

    while( !isdigit( s[ cnt ] ) )
        if( ++cnt == MAX ) {

            fread( s, 1, MAX, stdin );
            cnt = 0;
        }
    val = 0;
    while( isdigit( s[ cnt ] ) ) {

        val = val*10 + s[ cnt ] - '0';
        if( ++cnt == MAX ) {

            fread( s, 1, MAX, stdin );
            cnt = 0;
        }
    }
}

int main() {

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

    int i, x, y, tip;

    cnt = MAX-1;
    read( N );
    read( M );

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

    while( M-- ) {

        read( tip );
        read( x );
        read( 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;
}