Cod sursa(job #3317581)

Utilizator RaresVilcuVilcu Rares Andrei RaresVilcu Data 24 octombrie 2025 15:17:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

const int NMAX = 100000;
int par[NMAX + 1], m[NMAX + 1];

int root(int a) {
    int r = a;
    while (par[r] != r) r = par[r];
    while (a != r) {
        int t = par[a];
        par[a] = r;
        a = t;
    }
    return r;
}

void join(int a, int b) {
    a = root(a);
    b = root(b);
    if (a == b) return;
    if (m[a] < m[b]) swap(a, b);
    par[b] = a;
    m[a] += m[b];
}

int main() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    int n, q;
    fin >> n >> q;

    for (int i = 1; i <= n; ++i) {
        par[i] = i;
        m[i] = 1;
    }

    while (q--) {
        int t, x, y;
        fin >> t >> x >> y;
        if (t == 1)
            join(x, y);
        else
            fout << (root(x) == root(y) ? "DA\n" : "NU\n");
    }

    return 0;
}