Cod sursa(job #1656091)

Utilizator xtreme77Patrick Sava xtreme77 Data 18 martie 2016 18:46:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>

using namespace std;

ifstream cin ( "disjoint.in" ) ;
ofstream cout ( "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 ] ;
    }
    while ( nod != tata [ nod ] )
    {
        int aux = tata [ nod ] ;
        tata [ nod ] = R ;
        nod = aux ;
    }
    return R ;
}

inline void unite ( int x , int y )
{
    x = stramos ( x ) ;
    y = stramos ( y ) ;
    if ( x == y ) {
        return ;
    }
    if ( rang [ x ] > rang [ y ] ) {
        tata [ y ] = tata [ x ] ;
        rang [ x ] += rang [ y ] ;
    }
    else {
        tata [ x ] = tata [ y ] ;
        rang [ y ] += rang [ x ] ;
    }
}

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