Cod sursa(job #2757926)

Utilizator pokermon2005paun darius alexandru pokermon2005 Data 7 iunie 2021 17:43:31
Problema Sortare prin comparare Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

vector < int > disjointSet;

int getRoot(int x) {

    int root = x;

    for(;disjointSet[root] > 0;root = disjointSet[root]);

    return root;
}

void unify(int x, int y) {

    int rootX = getRoot(x);
    int rootY = getRoot(y);

    if(-disjointSet[rootX] < -disjointSet[rootY])
        swap(rootX, rootY);

    disjointSet[rootX] += disjointSet[rootY];
    disjointSet[rootY]  = rootX;
}

bool sameRoot(int x, int y) {
    return getRoot(x) == getRoot(y);
}

int main() {

    int n, m;
    f >> n >> m;

    disjointSet.resize(n + 1, -1);
    for(;m--;) {

        int q, x, y;
        f >> q >> x >> y;

        switch (q) {
            case 1:
                unify(x, y);
                break;
            case 2:
                g << (sameRoot(x, y) ? "DA" : "NU") << '\n';
                break;
            default:
                return 0;
        }
    }

    return 0;
}