Cod sursa(job #3357538)

Utilizator NadirSaleh Nadir Nadir Data 10 iunie 2026 22:38:14
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;

struct DSU{
    vector<int> p, sz;

    DSU(int n)
    {
        p.resize(n + 1);
        sz.resize(n + 1);
        for (int i = 1; i <= n; ++i)
        {
            p[i] = i;
            sz[i] = 1;
        }
    }

    int find_parent(int x)
    {
        if (p[x] == x)
            return x;

        p[x] = find_parent(p[x]);
        return p[x];
    }

    void unite(int x, int y)
    {
        x = find_parent(x);
        y = find_parent(y);

        if (x == y)
            return;

        if (sz[x] > sz[y])
            swap(x, y);

        p[x] = y;
        sz[y] += sz[x];
    }
};

int n, m;

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

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

    while (m--)
    {
        int t, x, y;
        cin >> t >> x >> y;

        if (t == 1)
        {
            dsu.unite(x, y);
        }
        else
        {
            if (dsu.find_parent(x) == dsu.find_parent(y))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }
}