Cod sursa(job #2788646)

Utilizator qubitrubbitQubit Rubbit qubitrubbit Data 26 octombrie 2021 10:37:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb

#include <fstream>
#include <set>
using namespace std;

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

const int CAPACITY = 100013;

class DisjointForests
{
private:
    int n;
    int root[CAPACITY];

public:
    DisjointForests(int n)
    {
        this->n = n;
        for (int i = 1; i <= n; ++i)
        {
            root[i] = i;
        }
    }

    void join(int x, int y)
    {
        int rootX = getRoot(x);
        int rootY = getRoot(y);
        root[rootX] = rootY;
    }

    int getRoot(int x)
    {
        return x == root[x] ? x : root[x] = getRoot(root[x]);
    }
};

int n, m, op, x, y;
int main()
{
    fin >> n >> m;
    DisjointForests forests(n);
    while (m-- > 0)
    {
        fin >> op >> x >> y;
        if (op == 1)
        {
            forests.join(x, y);
        }
        else if (op == 2)
        {
            fout << (forests.getRoot(x) == forests.getRoot(y) ? "DA" : "NU") << "\n";
        }
    }

    return 0;
}