Cod sursa(job #2079864)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 1 decembrie 2017 21:48:28
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
using namespace std;

class disjoint_set_union {
public:
    disjoint_set_union(size_t size) :
            data_(size, -1) {
    }

    void join(int x, int y) {
        x = get_root(x);
        y = get_root(y);

        if (x == y)
            return;

        //join by rank
        if (data_[x] < data_[y]) {
            data_[x] += data_[y];
            data_[y] = x;
        }
        else {
            data_[y] += data_[x];
            data_[x] = y;
        }
    }

    bool query(int x, int y) {
        return get_root(x) == get_root(y);
    }

private:
    int get_root(int x) {
        //find root
        int aux = x;
        while (data_[x] > 0)
            x = data_[x];
        int root = x;

        //compress
        x = aux;
        while (x != root) {
            aux = data_[x];
            data_[x] = root;
            x = aux;
        }

        return root;
    }

    vector< int > data_;
};

void solve() {
    size_t element_count, query_count;
    cin >> element_count >> query_count;

    disjoint_set_union dsu(element_count + 1);
    while (query_count--) {
        int operation, x, y;
        cin >> operation >> x >> y;

        if (operation == 1)
            dsu.join(x, y);
        else
            cout << (dsu.query(x, y) ? "DA" : "NU") << '\n';
    }
}

int main() {
    assert(freopen("disjoint.in", "r", stdin));
    assert(freopen("disjoint.out", "w", stdout));
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);

    solve();

    return 0;
}