Cod sursa(job #1929190)

Utilizator cristicretancristi cretan cristicretan Data 17 martie 2017 11:33:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
#define NMax 100001
using namespace std;

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

int rang[NMax], point[NMax];
int n, m, cod, x, y;

void unite(int x, int y)
{
    if(rang[x] > rang[y]) point[y] = x;
    else point[x] = y;

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

int verif(int x)
{
    int R, y;

    for(R = x; point[R] != R; R = point[R]); /// parcurg arborele


    /// compresia drumurilor
    for(; point[x] != x;)
    {
        y = point[x];
        point[x] = R;
        x = y;
    }
    return R;
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        point[i] = i;
        rang[i] = 1;
    }

    for(int i = 1; i <= m; ++i)
    {
        f >> cod >> x >> y;
        if(cod == 2)
        {
            if(verif(x) == verif(y)) g << "DA" << '\n';
            else g << "NU" << '\n';
        }
        else
        {
            unite(verif(x), verif(y));
        }
    }
    return 0;
}