Cod sursa(job #2445234)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 3 august 2019 11:29:41
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>

using namespace std;

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

const int NMAX = 1e5;

int N, M;
int dad[NMAX + 5], rnk[NMAX + 5];

int root(int node)
{
    int initnode = node, d = dad[node];

    while(node != d)
    {
        node = d;
        d = dad[node];
    }

    dad[initnode] = d;
    return d;
}

void join(int x, int y)
{
    x = root(x);
    y = root(y);

    if(rnk[x] < rnk[y])
        dad[x] = y;
    else if(rnk[x] > rnk[y])
        dad[y] = x;
    else
        rnk[x]++, dad[y] = x;
}

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

    for(int i = 1; i <= N; i++)
        dad[i] = i;

    for(int i = 1; i <= M; i++)
    {
        int t, x, y;
        fin >> t >> x >> y;

        if(t == 1)
            join(x, y);
        else
        {
            if(root(x) == root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    return 0;
}