Cod sursa(job #1655580)

Utilizator AdrianGotcaAdrian Gotca AdrianGotca Data 18 martie 2016 08:33:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>

using namespace std;

int h[100005],tata[100005],n,m,x,a,b;
void UNION(int,int);
int FIND(int);
int main(){
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;i++){
        scanf("%d%d%d",&x,&a,&b);
        if (x==1){
            UNION(a,b);
        }
        else {
            if (FIND(a)==FIND(b)){
                printf("DA\n");
            }
            else {
                printf("NU\n");
            }
        }
    }
    return 0;
}

void UNION(int x,int y){
    int rx=FIND(x);
    int ry=FIND(y);
    if (h[rx]>=h[ry]){
        tata[ry]=rx;
    }
    else {
        tata[rx]=ry;
    }
    if (h[rx]==h[ry]){
        h[rx]++;
    }
}

int FIND(int x){
    int cx=x;
    while (tata[x]){
        x=tata[x];
    }
    while (tata[cx]){
        int y=tata[cx];
        tata[cx]=x;
        cx=y;
    }
    return x;
}