Cod sursa(job #2817509)

Utilizator schizofrenieShallan Davar schizofrenie Data 13 decembrie 2021 19:08:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <bits/stdc++.h>

std::vector<int> jumpback;

int
root (int node) {
    if (jumpback[node] != node)
        jumpback[node] = root(jumpback[node]);
    return jumpback[node];
}

void
join (int a, int b) {
    int ra = root(a), rb = root(b);
    jumpback[rb] = ra;
}

int main () {
    int n, q;

    std::ifstream f("disjoint.in");
    std::ofstream g("disjoint.out");

    f >> n >> q;

    jumpback.resize(n);
    for (int i = 0; i != n; ++ i)
        jumpback[i] = i;

    for (int i = 0; i != q; ++ i) {
        int tip, a, b;
        f >> tip >> a >> b;
        -- a, -- b;
        if (tip == 1)
            join(a, b);
        else
            g << (root(a) == root(b) ? "DA\n" : "NU\n");
    }
}