Cod sursa(job #3197493)

Utilizator AlexNeaguAlexandru AlexNeagu Data 26 ianuarie 2024 22:59:15
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
using namespace std;

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

#define cin in 
#define cout out 

class DSU {
    int n;
    vector<int> par, size;
public:
    DSU(int _n) : n(_n) {
        par.resize(n + 1);
        for (int i = 1; i <= n; ++i) {
            par[i] = i;
        }
        size.assign(n + 1, 1);
    }
    int getRoot(int x) {
        int root = x;
        while (root != par[root]) {
            root = par[root];
        }
        while (x != par[x]) {
            int aux = par[x];
            par[x] = root;
            x = aux;
        }
        return root; 
    }

    bool unite(int x, int y) {
        x = getRoot(x);
        y = getRoot(y);
        if (x == y) {
            return false;
        }
        if (size[x] >= size[y]) {
            swap(x, y);
        }
        par[x] = y;
        size[y] += size[x];
        return true;
    }
};

int main() {
    int N, M;
    cin >> N >> M;
    DSU dsu(N);

    for (int i = 1; i <= M; ++i) {
        int x, y, op;
        cin >> op >> x >> y;
        if (op == 1) {
            dsu.unite(x, y);
        }
        else {
            x = dsu.getRoot(x);
            y = dsu.getRoot(y);
            x == y ? cout << "DA\n" : cout << "NO\n";
        }
    }
}