Cod sursa(job #1449940)

Utilizator ovidiuz98Zamfir Ovidiu ovidiuz98 Data 10 iunie 2015 23:19:27
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#define DIM 100003

using namespace std;

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

int nr[DIM],T[DIM],N,M,x,y,z;

int root(int x){
    int ret = x ;

    while(T[ret] != ret)
        ret = T[ret];

    int current = x ;
    while(T[current] != current){
        int aux = T[current];
        T[current] = ret;
        current = aux ;
    }
    return ret;

}

void connect( int x, int y){
    int a = root(x);
    int b = root(y);
    if(nr[b] < nr[a]){
        nr[a] += nr[b];
        T[b] = a;
    }
    else{
        nr[b] += nr[a];
        T[a] = b;
    }
}
int main(){

    fin >> N >> M ;

    for ( int i = 1 ; i <= N ;i++ ){
        T[i] = i;
        nr[i] = 1;
    }
    while( M -- ){
        fin >> x >> y >> z ;
        if( x == 1 ){
            connect(y , z);
        }
        else{
            if(root(y) == root(z))
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }
    }

    fin.close();fout.close();

    return 0;
}