Cod sursa(job #1702445)

Utilizator xtreme77Patrick Sava xtreme77 Data 15 mai 2016 11:12:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
/**
 * Code by Patrick Sava
 * "Spiru Haret" National College of Bucharest
 **/

#include <bits/stdc++.h>

using namespace std;

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

const int MAX = 1e5 + 14 ;

int tata [ MAX ] ;
int rang [ MAX ] ;

int stramos ( int nod )
{
    int R = nod ;
    while ( R != tata [ R ] ) {
        R = tata [ R ] ;
    }
    /*** aflam tatal multimii ***/
    while ( nod != tata [ nod ] ) {
        int aux = tata [ nod ] ;
        tata [ nod ] = R ;
        nod = aux ;
    }
    return R ;
}

void unite ( int x , int y )
{
    x = stramos ( x ) ;
    y = stramos ( y ) ;

    if ( x == y ) {
        return ;
    }

    if ( rang [ x ] > rang [ y ] ) {
        rang [ x ] += rang [ y ] ;
        tata [ y ] = tata [ x ] ;
    }
    else {
        rang [ y ] += rang [ x ] ;
        tata [ x ] = tata [ y ] ;
    }
}

int main()
{
    int n , m ;
    fin >> n >> m ;
    for ( int i = 1 ; i <= n ; ++ i ) {
        tata [ i ] = i ;
        rang [ i ] = 1 ;
    }
    while ( m -- )
    {
        int tip ;
        fin >> tip ;
        if ( tip == 1 ) {
            int x , y ;
            fin >> x >> y ;
            unite ( x , y ) ;
        }
        else {
            int x , y ;
            fin >> x >> y ;
            if ( stramos ( x ) == stramos ( y ) ) {
                fout << "DA\n" ;
            }
            else {
                fout << "NU\n" ;
            }
        }
    }
    return 0;
}