Cod sursa(job #3357946)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:06:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>

using namespace std;

int parent[100005];
int rank_set[100005];

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

void union_sets(int x, int y) {
    x = find_set(x);
    y = find_set(y);
    if (x != y) {
        if (rank_set[x] < rank_set[y])
            swap(x, y);
        parent[y] = x;
        if (rank_set[x] == rank_set[y])
            rank_set[x]++;
    }
}

int main() {
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");

    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++) {
        parent[i] = i;
        rank_set[i] = 0;
    }

    for (int i = 0; i < m; i++) {
        int op, x, y;
        cin >> op >> x >> y;
        if (op == 1) {
            union_sets(x, y);
        } else {
            if (find_set(x) == find_set(y)) {
                cout << "DA\n";
            } else {
                cout << "NU\n";
            }
        }
    }

    return 0;
}