Cod sursa(job #2346304)

Utilizator petru.ciocirlanPetru Ciocirlan petru.ciocirlan Data 17 februarie 2019 15:22:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
using namespace std;

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

const int MAXNM = 100000 + 16;
int Root[MAXNM], Rank[MAXNM];
int N, M;

int forest_find(int x)
{
    int R = 0;
    for(R = Root[x]; R != Root[R]; R = Root[R]);

    while(x != R)
    {
        int dad = Root[x];
        Root[x] = R;
        x = dad;
    }

    return R;
}

void forest_unite(int x, int y)
{
    if(Rank[x] < Rank[y])
        Root[x] = Root[y];
    else
        Root[y] = Root[x];

    if(Rank[x] == Rank[y])
        ++Rank[x];
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= N; ++i)
        Root[i] = i, Rank[i] = 1;

    while(M--)
    {
        int tip, x, y;
        fin >> tip >> x >> y;

        if(tip == 1)
        {
            forest_unite(forest_find(x), forest_find(y));
        }
        else
        {
            if(forest_find(x) == forest_find(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    return 0;
}