Cod sursa(job #2086949)

Utilizator cristicretancristi cretan cristicretan Data 12 decembrie 2017 18:30:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
/// DISJOINT SET OF TREES || PADURI DE MULTIMI DISJUNCTE
#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>
#include <map>
#include <utility>
#define NMax 100001
///#define f cin
///#define g cout
using namespace std;

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

int n, m, cod, x, y, rootx, rooty;
int rang[NMax], root[NMax];

int findroot(int x) /// gasesc radacina
{
    while(x != root[x])
        x = root[x];
    return x;
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i) /// fac toate nodurile sa pointeze catre ele si le fac rangul 1
    {
        rang[i] = 1;
        root[i] = i;
    }
    for(int i = 1; i <= m; ++i)
    {
        f >> cod;
        f >> x >> y;
        rootx = findroot(x);
        rooty = findroot(y);
        if(cod == 1)
        {
            if(rang[rootx] > rang[rooty]) /// unesc elementele la multimea cu rangul mai mare
            {
                rang[rootx] += rang[rooty]; /// adaug rangul celeilalte la multimea curenta
                root[rooty] = rootx; /// parent-ul multimii unite devine parentul multii la care e unita
            }
            else
            {
                rang[rooty] += rang[rootx];
                root[rootx] = rooty;
            }
        }
        else
        {
            if(rootx == rooty) g << "DA" << '\n';
            else g << "NU" << '\n';
        }
    }
    return 0;
}