Cod sursa(job #3315186)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 12 octombrie 2025 20:57:09
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <cstdio>
#include <vector>
using namespace std;

const int NMAX = 100005;

vector<int> tata(NMAX, -1);
vector<int> height(NMAX, 1);

int Reprezentant(int nod) {
    if (tata[nod] == -1)
        return nod;
    tata[nod] = Reprezentant(tata[nod]);
    return tata[nod];
}

void Reuniune(int nod1, int nod2) {
    int reprezentant1 = Reprezentant(nod1);
    int reprezentant2 = Reprezentant(nod2);


    if (height[reprezentant1] > height[reprezentant2]) {
        tata[reprezentant2] = reprezentant1;
    } else if (height[reprezentant1] < height[reprezentant2]) {
        tata[reprezentant1] = reprezentant2;
    } else {
        tata[reprezentant2] = reprezentant1;
        height[reprezentant1]++;
    }
}

bool Aceeasi_Multime(int nod1, int nod2) {
    return Reprezentant(nod1) == Reprezentant(nod2);
}

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

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

    for (int i = 0; i < m; i++) {
        int op, nod1, nod2;
        scanf("%d %d %d", &op, &nod1, &nod2);

        if (op == 1)
            Reuniune(nod1, nod2);
        else
            printf(Aceeasi_Multime(nod1, nod2) ? "DA\n" : "NU\n");
    }

    return 0;
}