Cod sursa(job #1119218)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 24 februarie 2014 16:17:20
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.16 kb
#include <stdio.h>
#define N_MAX 100000
typedef char bool;

int N, M;
int up[ N_MAX + 1 ], h[ N_MAX + 1 ];

int getroot( int x ) {
    int root;
    for( root = x; up[ root ] != root; root = up[ root ] );
    
    int y;
    while( up[ x ] != x ) {
        y = up[ x ];
        up[ x ] = root;
        x = y;
    }
    return root;
}

void unify( int x, int y ) {
    int rx = getroot( x ), ry = getroot( y );
    if( h[ rx ] > h[ ry ] ) {
        up[ ry ] = up[ rx ];
    } else {
        up[ rx ] = up[ ry ];
    }
    if( h[ rx ] == h[ ry ] ) {
        h[ ry ] ++;
    }
}

bool seteq( int x, int y ) {
    return getroot( x ) == getroot( y );
}

int main( ) {
    FILE * fin, * fout;
    fin = fopen( "disjoint.in", "r" );
    fout = fopen( "disjoint.out", "w" );

    fscanf( fin, "%d%d", &N, &M );

    int i;
    for( i = 1; i <= N; i ++ ) {
        up[ i ] = i;
        h[ i ] = 1;
    }

    for( i = 1; i <= M; i ++ ) {
        int type, x, y;
        fscanf( fin, "%d%d%d", &type, &x, &y );
        if( type == 1 ) {
            unify( x, y );
        } else {
            fprintf( fout, seteq( x, y ) ? "DA\n" : "NU\n" );
        }
    }

    fclose( fin );
    fclose( fout );
}