Cod sursa(job #2940648)

Utilizator AndreiAncutaAndrei Ancuta AndreiAncuta Data 16 noiembrie 2022 01:17:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <algorithm>
#include <fstream>
#include <limits>
#include <vector>

using std::vector;

template <class T> class DSU {
    vector<T> parent;
    vector<int> height;

public:
    DSU(int setCount) {
        parent.resize(setCount + 1);
        height.resize(setCount + 1, 0);
    }

    void makeSet(T x) { parent[x] = x; }

    T getRepr(T x) {
        if (parent[x] == x) {
            return x;
        }
        return parent[x] = getRepr(parent[x]);
    }

    void unite(T x, T y) {
        auto xr = getRepr(x);
        auto yr = getRepr(y);
        if (height[xr] < height[yr]) {
            parent[yr] = xr;
            if (height[xr] == height[yr]) height[xr]++;
        } else {
            parent[xr] = yr;
            if (height[xr] == height[yr]) height[yr]++;
        }
    }
};

int main() {
    std::ifstream fin("disjoint.in");

    int setCount, opCount;
    fin >> setCount >> opCount;

    DSU<int> dsu(setCount);
    for (int i = 1; i <= setCount; ++i) {
        dsu.makeSet(i);
    }

    std::ofstream fout("disjoint.out");

    for (int i = 0; i < opCount; ++i) {
        int op, x, y;
        fin >> op >> x >> y;

        if (op == 1) {
            dsu.unite(x, y);
        } else {
            if (dsu.getRepr(x) == dsu.getRepr(y)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }

    fin.close();
    fout.close();

    return 0;
}