Cod sursa(job #2735848)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 2 aprilie 2021 21:27:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>

using namespace std;

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

class disjoint_set
{
    private:
        int size;
        int* parent;
        int* h;

    public:
        disjoint_set();
        disjoint_set(const int _SIZE);
        ~disjoint_set();
        int Find(const int x);
        void Union(const int x, const int y);
};

disjoint_set :: disjoint_set()
{
    size = 0;
    parent = NULL;
    h = NULL;
}

disjoint_set :: disjoint_set(const int _SIZE)
{
    size = _SIZE;
    parent = new int[_SIZE + 1];
    h = new int[_SIZE + 1];

    for (int i = 1; i <= _SIZE; i++)
    {
        parent[i] = i;
        h[i] = 0;
    }
}

disjoint_set :: ~disjoint_set()
{
    delete[] parent;
    delete[] h;
}

int disjoint_set :: Find(const int x)
{
    if (parent[x] == x)
        return x;

    parent[x] = Find(parent[x]);

    return parent[x];
}

void disjoint_set :: Union(const int x, const int y)
{
    int px = Find(x);
    int py = Find(y);

    if (px == py)
        return;

    if (h[px] < h[py])
        parent[px] = py;
    else if (h[px] > h[py])
        parent[py] = px;
    else
    {
        parent[py] = px;
        h[px]++;
    }
}

int main()
{
    int n; f >> n;

    disjoint_set ds(n);

    int m; f >> m;

    while (m--)
    {
        int type, x, y; f >> type >> x >> y;

        if (type == 1)
        {
            ds.Union(x, y);
        }
        else
        {
            if (ds.Find(x) == ds.Find(y))
                g << "DA\n";
            else
                g << "NU\n";
        }
    }

    return 0;
}