Cod sursa(job #2954796)

Utilizator erwin12511Brustur Erwin erwin12511 Data 15 decembrie 2022 12:49:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

std::vector<int> jumpback;

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


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);
    int rb = root(b);
    jumpback[rb] = ra;
}

int main() {
    int n, q;

    fin >> 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;
        fin >> tip >> a >> b;
        a = a - 1;
        b = b - 1;
        if (tip == 1)
            join(a, b);
        else
            fout << (root(a) == root(b) ? "DA\n" : "NU\n");
    }
}