Cod sursa(job #2028276)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 27 septembrie 2017 16:30:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <cstdio>

using namespace std;

class Disjoint{
private:
    int parents[100005];
    int depths[100005];

    int getParent(int x){
        int initialX = x;

        while(parents[x] != x){
            x = parents[x];
        }

        while(parents[initialX] != initialX){
            parents[initialX] = x;
            initialX = parents[initialX];
        }

        return x;
    }

public:

    Disjoint(int n = 100005){
        for(int i = 0; i < n; i++){
            parents[i] = i;
            depths[i] = 1;
        }
    }

    bool areInTheSameGroup(int x, int y){
        if(getParent(x) == getParent(y)){
            return true;
        }

        return false;
    }

    void join(int x, int y){
        x = getParent(x);
        y = getParent(y);

        if(depths[x] < depths[y]){
            parents[x] = y;
        }
        else if(depths[x] > depths[y]){
            parents[y] = x;
        }
        else{
            parents[x] = y;
            depths[y]++;
        }
    }
};

int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    int n, m;
    scanf("%d %d", &n, &m);
    Disjoint a;

    for(int i = 0; i < m; i++){
        int tmp1, tmp2, tmp3;
        scanf("%d %d %d", &tmp1, &tmp2, &tmp3);

        if(tmp1 == 1){
            a.join(tmp2, tmp3);
        }
        else if(tmp1 == 2) {
            if (a.areInTheSameGroup(tmp2, tmp3) == true) {
                printf("DA\n");
            }
            else{
                printf("NU\n");
            }
        }

    }


    return 0;
}