Cod sursa(job #2121061)

Utilizator SolcanMihaiSolcan Mihai Andrei SolcanMihai Data 3 februarie 2018 11:33:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>

using namespace std;

struct Padure{
    int tata[100005];
    int depth[100005];
    int n;

    Padure(int dimensiune){
        n = dimensiune;

        for(int i = 0; i < n; i++){
            tata[i] = i;
            depth[i] = 1;
        }
    }

    int findTata(int x){
        int xx = x;

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

        tata[xx] = x;

        return x;
    }

    bool inSameGroup(int x, int y){
        if(findTata(x) == findTata(y)){
            return true;
        }
        else{
            return false;
        }
    }

    void reunire(int x, int y){
        x = findTata(x);
        y = findTata(y);

        if(depth[x] > depth[y]){
            tata[y] = x;
        }
        else if(depth[x] < depth[y]){
            tata[x] = y;
        }
        else{
            tata[y] = x;
            depth[x]++;
        }
    }
};

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

    int n, m;
    int tmp1, tmp2, tmp3;
    scanf("%d %d", &n, &m);

    Padure padure = Padure(n);

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

        if(tmp1 == 1){
            padure.reunire(tmp2, tmp3);
        }
        else if(tmp1 == 2){
            if(padure.inSameGroup(tmp2, tmp3)){
                printf("DA\n");
            }
            else{
                printf("NU\n");
            }
        }
    }

    return 0;
}