Cod sursa(job #3371384)

Utilizator Andreea345Vaduva Andreea Andreea345 Data 30 octombrie 2026 08:25:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 100001;
int p[NMAX], sz[NMAX];

int Find(int x) {
    int r = x;
    while (r != p[r]) {
        r = p[r];
    }
    while (x != r) {
        int nxt = p[x];
        p[x] = r;
        x = nxt;
    }
    return r;
}

void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if (x == y) return;
    if (sz[x] < sz[y]) {
        p[x] = y;
        sz[y] += sz[x];
    } else {
        p[y] = x;
        sz[x] += sz[y];
    }
}

int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; ++i) {
        p[i] = i;
        sz[i] = 1;
    }
    for (int i = 1; i <= q; ++i) {
        int op, x, y;
        cin >> op >> x >> y;
        if (op == 1) {
            Union(x, y);
        } else {
            if (Find(x) == Find(y)) {
                cout << "DA\n";
            } else {
                cout << "NU\n";
            }
        }
    }
    return 0;
}