Cod sursa(job #2338134)

Utilizator AndreiBadescuBadescu Andrei-Octavian AndreiBadescu Data 7 februarie 2019 03:07:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>

using namespace std;
typedef unsigned int uint;

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

struct subset
{
    uint root,rank;
};

uint Find(uint x, subset DJ[])
{
    if (DJ[x].root != x)
        DJ[x].root = Find(DJ[x].root, DJ);

    return DJ[x].root;
}

void Union(uint x, uint y, subset DJ[])
{
    x = Find(x,DJ), y = Find(y,DJ);
    if (DJ[x].rank < DJ[y].rank)
    {
        DJ[x].rank += DJ[y].rank;
        DJ[y].root = x;
    }
    else
    {
        DJ[y].rank += DJ[x].rank;
        DJ[x].root = y;
    }
}

int main()
{
    uint n,m;
    fin >> n >> m;

    subset DJ[n + 1];

    for (uint i = 1; i <= n; ++i)
    {
        DJ[i].root = i;
        DJ[i].rank = 1;
    }

    for (uint c,x,y,i = 0; i < m; ++i)
    {
        fin >> c >> x >> y;
        if (c == 1)
            Union(x,y,DJ);
        else
        {
            if (Find(x,DJ) == Find(y,DJ))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
}