Cod sursa(job #3350681)

Utilizator Alex_at_gameIustin-Alexandru Frateanu Alex_at_game Data 11 aprilie 2026 19:33:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(v) begin(v), end(v)
#define al(v, l, r) begin(v) + l, begin(v) + r + 1
#define sz(v) (int)v.size()
#define pb push_back
#define pob pop_back
#define fs first
#define sd second

constexpr int inf = 2e9;
constexpr ll infll = 4e18;

struct DSU {
    int n;
    vector<int> p, dim;

    DSU(int n): p(n + 1), dim(n + 1, 1) {
        iota(all(p), 0);
    }

    inline int find(int x) {
        return x == p[x] ? x : p[x] = find(p[x]);
    }

    inline bool unite(int a, int b) {
        a = find(a);
        b = find(b);

        if (a == b) {
            return false;
        }

        if (dim[a] < dim[b]) {
            swap(a, b);
        }

        p[b] = a;
        dim[a] += dim[b];
        return true;
    }
};

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

    cin >> n >> m;
    DSU dsu(n);

    for (int i = 0, tip, x, y; i < m; ++i) {
        cin >> tip >> x >> y;

        if (tip == 1) {
            dsu.unite(x, y);
        } else {
            cout << (dsu.find(x) == dsu.find(y) ? "DA\n" : "NU\n");
        }
    }
}