Cod sursa(job #3310465)

Utilizator pkseVlad Bondoc pkse Data 14 septembrie 2025 10:11:36
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

struct DSU {
    vector<int> a, cnt;

    DSU(int n) {
        for(int i = 0; i < n; i ++) {
            a.push_back(i);
            cnt.push_back(1);
        }
    }

    int leader(int x) {
        if(a[x] == x)
            return x;
        return a[x] = leader(a[x]);
    }

    int query(int x, int y) {
        x = leader(x);
        y = leader(y);
        if(x == y)
            return true;
        return false;
    }

    void merge(int x, int y) {
        if(query(x, y))
            return;
        x = leader(x);
        y = leader(y);
        if(cnt[x] < cnt[y])
            swap(x, y);
        a[y] = x;
        cnt[x] += cnt[y];
    }
};

int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n, q; cin >> n >> q;
    DSU dsu(n);
    for(int i = 0; i < q; i ++) {
        int code, x, y; cin >> code >> x >> y;
        x --; y --;
        if(code == 1) {
            dsu.merge(x, y);
        } else {
            if(dsu.query(x, y))
                cout << "DA\n";
            else 
                cout << "NU\n";
        }
    }
}