Cod sursa(job #3358486)

Utilizator NFJJuniorIancu Ivasciuc NFJJunior Data 17 iunie 2026 00:39:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
// Disjoint Set Union
//
// Graph data structure that provides the following operations:
// - union -> union two sets together
// - find -> for two different nodes, find if they are in the same strongly
// connected component
//
// Complexity: almost O(1)

#include <bits/stdc++.h>
using namespace std;

int n, m;
vector<int> parent;
vector<int> depth;

void make_set(int node)
{
    parent[node] = node;
    depth[node] = 0;
}

int find_set(int node)
{
    if (node == parent[node])
        return node;
    return parent[node] = find_set(parent[node]);
}

void union_sets(int node1, int node2)
{
    int p1 = find_set(node1);
    int p2 = find_set(node2);
    if (p1 == p2)
        return;

    if (depth[p1] < depth[p2])
        swap(p1, p2);
    if (depth[p1] == depth[p2])
        depth[p1]++;

    parent[p2] = p1;
}

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

    cin >> n >> m;
    parent.resize(n);
    depth.resize(n);

    for (int i = 0; i < n; i++)
        make_set(i);

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

        if (op == 1) {
            union_sets(x, y);
        } else {
            cout << (find_set(x) == find_set(y) ? "DA\n" : "NU\n");
        }
    }

    return 0;
}