Cod sursa(job #2870790)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 12 martie 2022 16:04:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>

using namespace std;

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

class disjoint_set
{
    private:
        int set_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()
{
    set_size = 0;
    parent = NULL;
    h = NULL;
}

disjoint_set :: disjoint_set(const int _SIZE)
{
    set_size = _SIZE;

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

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

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 if (h[px] == h[py])
    {
        parent[px] = py;
        h[py]++;
    }
}

int n, m;

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

    disjoint_set ds(n);

    for (int i = 1; i <= m; i++)
    {
        int type, x , y; f >> type >> x >> y;

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

    return 0;
}