Cod sursa(job #2227916)

Utilizator inquisitorAnders inquisitor Data 2 august 2018 10:42:09
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <stdio.h>

#define NMAX 100020

int TT[NMAX], RG[NMAX];
int N, M, p = -1;

char buffer[1400000];

__attribute__((always_inline)) int get_int()
{
    int number = 0;

    for(++p; buffer[p] > 47; ++p)
    {
        number = number * 10 + buffer[p] - 48;
    }

    return number;
}

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

    //merg in sus pe arbore pana gasesc un nod care pointeaza catre el insusi
    for (R = x; TT[R] != R; R = TT[R]);

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

void unite(int x, int y)
{
    //unesc multimea cu rang mai mic de cea cu rang mai mare
    if (RG[x] > RG[y])
        TT[y] = x;
            else TT[x] = y;

    //in caz ca rangurile erau egale atunci cresc rangul noii multimi cu 1
    if (RG[x] == RG[y]) RG[y]++;
}

int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    N = get_int(); M = get_int();

    int i, x, y, cd;

    //initial fiecare nod pointeaza catre el insusi iar rangul fiecarui arbore este 1
    for (i = 1; i <= N; i++)
    {
        TT[i] = i;
        RG[i] = 1;
    }

    for (i = 1; i <= M; i++)
    {
        cd = get_int();

        x = get_int();

        y = get_int();

        if (cd == 2){
            //verific daca radacina arborilor in care se afla x respectiv y este egala
            if (find(x) == find(y)) printf("DA\n");
                else printf("NU\n");
        }
            else //unesc radacinile arborilor corespunzatori multimilor nodurilor x respectiv y
                {
                    if (find(x) == find(y))  {fprintf(stderr,"%d ", i);return 0;}
                    unite(find(x), find(y));
                }
    }

    return 0;
}