Cod sursa(job #2934654)

Utilizator BluThund3rRadu George BluThund3r Data 6 noiembrie 2022 10:50:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");

int n, m, cod, x, y;
vector<int> parent, height;

int rep(int x) {
    if (!parent[x])
        return x;
    
    int reprez = rep(parent[x]);
    parent[x] = reprez;
    return reprez;
}

void myUnion (int x, int y) {
    int repx = rep(x), repy = rep(y);

    if (height[repx] < height[repy])
        parent[repx] = repy;

    else if (height[repy] < height[repx])
        parent[repy] = repx;

    else {
        parent[repx] = repy;
        ++ height[repy];
    }
}

int main() {
    in >> n >> m;
    parent.resize(n + 1, 0);
    height.resize(n + 1, 0);

    while (m --) {
        in >> cod >> x >> y;
        if (cod == 1)
            myUnion(x, y);
        else
            out << ((rep(x) == rep(y))? "DA\n" : "NU\n");
    }

    return 0;
}