Cod sursa(job #3353450)

Utilizator filipdanieloanFilip-Daniel Oancea filipdanieloan Data 7 mai 2026 14:12:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
using namespace std;

constexpr int INF = 1e9;

vector<int> adincime, tata;

void unite(int x, int y) {
    tata[y] = x;
    adincime[x] = max(adincime[x], adincime[y] + 1);
    adincime[y] = INF;
}

signed main() {
#ifndef LOCAL
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
#endif

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m; cin >> n >> m;
    adincime.resize(n+1), tata.resize(n+1);
    while (m--) {
        int op, x, y; cin >> op >> x >> y;
        if (tata[x]) x = tata[x];
        if (tata[y]) y = tata[y];
        if (op == 1) {
            if (adincime[x] >= adincime[y])
                unite(x, y);
            else
                unite(y, x);
        } else {
            int absoluteDadX = x, absoluteDadY = y;
            vector<int> path;
            for (; tata[absoluteDadX]; absoluteDadX = tata[absoluteDadX]) {
                path.push_back(absoluteDadX);
            }
            for (auto& i : path)
                tata[i] = absoluteDadX;
            path.clear();
            for (; tata[absoluteDadY]; absoluteDadY = tata[absoluteDadY]) {
                path.push_back(absoluteDadY);
            }
            for (auto& i : path)
                tata[i] = absoluteDadY;
            cout << (absoluteDadX == absoluteDadY ? "DA" : "NU") << '\n';
        }
    }

    return 0;
}