Cod sursa(job #2247386)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 septembrie 2018 15:34:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>

using namespace std;

class Sets
{
public:
    Sets(int n) : fathers_(vector<int>(n, -1)) {}

    void Unite(int a, int b);

    bool SameGroup(int a, int b);

private:
    vector<int> fathers_;

    int get_root(int node);
};

void Sets::Unite(int a, int b)
{
    auto root_a = get_root(a);
    auto root_b = get_root(b);

    if (root_a != root_b) {
        fathers_[root_b] = root_a;
    }
}

bool Sets::SameGroup(int a, int b)
{
    return get_root(a) == get_root(b);
}

int Sets::get_root(int node)
{
    if (fathers_[node] == -1) {
        return node;
    }
    return fathers_[node] = get_root(fathers_[node]);
}

int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");

    int n, queries;
    fin >> n >> queries;

    Sets sets(n);
    for (int i = 0; i < queries; i += 1) {
        int type, a, b;
        fin >> type >> a >> b;

        if (type == 1) {
            sets.Unite(a - 1, b - 1);
        } else {
            fout << (sets.SameGroup(a - 1, b - 1) ? "DA" : "NU") << "\n";
        }
    }

    return 0;
}