Cod sursa(job #1638373)

Utilizator ovidiuz98Zamfir Ovidiu ovidiuz98 Data 7 martie 2016 22:47:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
#define DIM 100005

using namespace std;

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

int N,M;
int r[DIM],nr[DIM];

int root(int x){
    int z=x;
    while(r[z]!=z)
        z=r[z];
    while(x!=r[x]){
        int aux=x;
        x=r[x];
        r[aux]=z;
    }
    return z;
}

void join(int a,int b){
    int x=root(a),y=root(b);
    if(x==y)
        return ;
    if(nr[x]>=nr[y]){
        r[y]=r[x];
        nr[x]+=nr[y];
    }
    else{
        r[x]=r[y];
        nr[y]+=nr[x];
    }
}

void check(int a,int b){
    if(root(a)==root(b))
        fout << "DA\n";
    else
        fout << "NU\n";
}
int main(){

    fin >> N >> M;

    for(int i=1;i<=N;i++){
        r[i]=i;
        nr[i]=1;
    }

    while(M--){
        int a,b,c;
        fin >> a >> b >> c;
        if(a==1)
            join(b,c);
        else
            check(b,c);
    }

    return 0;

}