Cod sursa(job #3220625)

Utilizator MagicantPlusIuoras Andrei MagicantPlus Data 4 aprilie 2024 14:05:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

class DisjointSets
{
public:
    vector<int> father, setsize;

    DisjointSets();
    DisjointSets(int n);
    void unite(int x, int y);
    int find(int x);
};

int main()
{
    int n, q;

    fin >> n >> q;
    DisjointSets ds(n + 1);

    for(int i = 0; i < q; i++)
    {
        int type, x, y;

        fin >> type >> x >> y;

        if(type == 1)
        {
            ds.unite(x, y);
        }
        else
        {
            if(ds.find(x) == ds.find(y))
            {
                fout << "DA\n";
            }
            else
            {
                fout << "NU\n";
            }
        }
    }
    return 0;
}

DisjointSets::DisjointSets()
{

}
DisjointSets::DisjointSets(int n)
{
    this->father = vector<int>(n, -1);
    this->setsize = vector<int>(n, 1);
}
void DisjointSets::unite(int x, int y)
{
    int xRep, yRep;

    xRep = this->find(x);
    yRep = this->find(y);

    if(this->setsize[yRep] < this->setsize[xRep])
    {
        this->setsize[xRep] += this->setsize[yRep];
        this->setsize[yRep] = this->setsize[xRep];
        this->father[yRep] = xRep;
    }
    else
    {
        this->setsize[yRep] += this->setsize[xRep];
        this->setsize[xRep] = this->setsize[yRep];
        this->father[xRep] = yRep;
    }
}
int DisjointSets::find(int x)
{
    if(this->father[x] == -1)
        return x;

    int representative;

    representative = this->find(father[x]);

    this->father[x] = representative;
    return representative;
}