Cod sursa(job #3357431)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 9 iunie 2026 18:54:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>
using namespace std;


const int NMAX = 1e5;
int h[NMAX + 1], p[NMAX + 1];

int Find(int x) {//returneaza radacina arborelui in care se afla x
    while(x != p[x]) {
        x = p[x];
    }
    return x;
}

void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if(h[x] > h[y]) {
        p[y] = x;
        h[y] = 0; //optional
    } else {
        if(h[x] < h[y]) {
            p[x] = y;
            h[x] = 0;
        } else {
            p[y] = x;
            h[y] = 0;
            h[x]++;
        }
    }
}


int main() {
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; i++) {
        h[i] = 1;
        p[i] = i;
    }
    for(int i = 1; i <= m; i++) {
        int op, x, y;
        cin >> op >> x >> y;
        if(op == 1) {
            Union(x, y);
        } else {
            if(Find(x) != Find(y)) {
                cout << "NU\n";
            } else {
                cout << "DA\n";
            }
        }
    }
}