Cod sursa(job #3332906)

Utilizator Alex283810Mocan Alexandru Vali Alex283810 Data 9 ianuarie 2026 19:38:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>

int parent[100001];
int ranks[100001];
void make_set(int a)
{
    parent[a] = a;
}
int find_root(int a)
{
    if(a == parent[a])
        return a;
    return parent[a] = find_root(parent[a]);
}
void unire(int a, int b)
{
    int root_a = find_root(a);
    int root_b = find_root(b);
    if(root_a != root_b)
    {
        if(ranks[root_a] > ranks[root_b])
            parent[root_b] = root_a;
        else if(ranks[root_a] < ranks[root_b])
            parent[root_a] = root_b;
        else
        {
            parent[root_a] = root_b;
            ranks[root_b]++;
        }
    }

}
int main()
{
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

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

    int n, m;
    std::cin >> n >> m;
    for(int i = 1; i <= n; i ++)
        parent[i] = i;
    for(int i = 1; i <= m; i ++)
    {
        int op, a, b;
        std::cin >> op >> a >> b;
        if(op == 1)
        {
            unire(a, b);
        }
        else
        {
            if(find_root(a) == find_root(b))
            {
                std::cout << "DA\n";
            }
            else
                std::cout << "NU\n";
        }
    }

    return 0;
}