Cod sursa(job #2678703)

Utilizator Andrei1Mariciuc Andrei-Alexandru Andrei1 Data 28 noiembrie 2020 15:09:10
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

class DisjointSets {
private:
    vector<int> parent;
    vector<int> rank;

public:
    DisjointSets(int n) {
        for (int i = 0; i < n; i++)
            make_set(i);
    }

    ~DisjointSets() {
        parent.clear();
        rank.clear();
    }

    void make_set(int x) {
        parent.push_back(x);
        rank.push_back(0);
    }

    int find_set(int x) {
        vector<int> queue;
        while (parent[x] != x) {
            queue.push_back(x);
            x = parent[x];
        }

        for (int it: queue)
            parent[it] = x;

        queue.clear();

        return x;
    }

    void union_set(int x, int y) {
        int rx = find_set(x); // alias reprezentatnul lui x, respectiv y
        int ry = find_set(y);

        if (rank[rx] <= rank[ry]) {
            parent[rx] = ry;
            rank[rx] == rank[ry] ? rank[ry]++ : false;
        }
        else
            parent[ry] = rx;
    }

    void show() {
        for (int i = 0; i < parent.size(); i++)
            cout << i << " " << parent[i] << " " << rank[i] << endl;

    }
};

void solve(int n, int m) {
    DisjointSets disjointSets(n);
    int op;
    int x, y;
    for (int i = 0; i < m; i++) {
        cin >> op >> x >> y;
        switch (op) {
            case 1 :
                disjointSets.union_set(x - 1, y - 1);
                break;
            case 2 :
                cout << ((disjointSets.find_set(x - 1) == disjointSets.find_set(y - 1)) ? "DA" : "NU") << "\n";
        }
    }
}

int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    solve(n, m);
    return 0;
}