Cod sursa(job #1515916)

Utilizator jimcarterJim Carter jimcarter Data 2 noiembrie 2015 13:19:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <cstdio>
using namespace std;

FILE *f = fopen ( "disjoint.in" , "r" ) , *g = fopen ( "disjoint.out" , "w" );

const int MAX = 100005;
int N , M , i , root , x , y , Xfather , Yfather , father [ MAX ] , type;

int findRoot ( int node )
{
    if ( father [ node ] != node )
        return findRoot ( father [ node ] );
    else
    {
        root = node;
        return root;
    }
    father [ node ] = root;
}

void Union ( int Ltree , int Rtree )
{
    if ( Ltree == Rtree )
        return;
    father [ Rtree ] = Ltree;
}

void read()
{
    fscanf ( f , "%d %d" , &N , &M );
    for ( i = 1 ; i <= N ; father [ i ] = i , i ++ ); // set father [ i ] = i

    for ( i = 1 ; i <= M ; i ++ )
    {
        //get request
        fscanf ( f , "%d %d %d" , &type , &x , &y );
        Xfather = findRoot ( x );
        Yfather = findRoot ( y );

        if ( type == 1 )    //get the union of the trees containing x and y
            Union ( Xfather , Yfather );
        else                //check if x and y are in the same tree
            if ( Xfather == Yfather )
                fprintf ( g , "DA\n" );
            else
                fprintf ( g , "NU\n" );

    }
}

int main()
{
    read();
    return 0;
}