Cod sursa(job #1875827)

Utilizator alittlezzCazaciuc Valentin alittlezz Data 11 februarie 2017 17:08:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>

using namespace std;

int root[100005], depth[100005];

inline int getRoot(int x){
    if(root[x] != x){
        root[x] = getRoot(root[x]);
    }
    return root[x];
}

void unite(int x, int y){
    x = getRoot(x);
    y = getRoot(y);
    if(x == y){
        return;
    }
    if(depth[x] > depth[y]){
        root[y] = x;
    }else{
        root[x] = y;
    }
}

bool areUnion(int x, int y){
    x = getRoot(x);
    y = getRoot(y);
    return x == y;
}

int main(){
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    int n,m,i,op,x,y;
    scanf("%d %d", &n, &m);
    for(i = 1;i <= n;i++){
        root[i] = i;
        depth[i] = 1;
    }
    for(;m--;){
        scanf("%d %d %d", &op, &x, &y);
        if(op == 1){
            unite(x, y);
        }else{
            if(areUnion(x, y)){
                printf("DA");
            }else{
                printf("NU");
            }
            printf("\n");
        }
    }
    return 0;
}