Cod sursa(job #3352290)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 26 aprilie 2026 12:15:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 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 node) {
    if (tata[node] == -1) return node;
    tata[node] = Reprezentant(tata[node]);
    return tata[node];
}
void Reuniune(int node1, int node2) {
    int reprezentant1 = Reprezentant(node1);
    int reprezentant2 = Reprezentant(node2);

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

bool Aceeasi_Multime(int node1, int node2) {
    return (Reprezentant(node1) == Reprezentant(node2));
}

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;
}