Cod sursa(job #1889819)

Utilizator Burbon13Burbon13 Burbon13 Data 22 februarie 2017 21:34:09
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <cstdio>

using namespace std;

const int nmx = 100002;

int n,rang[nmx],tata[nmx];

void uneste(int g1, int g2)
{
    if(rang[g1] > rang[g2])
        tata[g2] = g1;
    else
        tata[g1] = g2;
    if(rang[g1] == rang[g2])
        ++ rang[g2];
}

int grupa(int nod)
{
    int aux = nod;

    while(aux != tata[aux])
        aux = tata[aux];

    while(nod != tata[nod])
    {
        int aux2 = tata[nod];
        tata[nod] = aux;
        nod = aux2;
    }

    return nod;
}

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

    int opr;
    scanf("%d %d", &n, &opr);

    for(int i = 1; i <= n; ++i)
    {
        tata[i] = i;
        rang[i] = 1;
    }

    while(opr--)
    {
        int o,x,y;
        scanf("%d %d %d", &o, &x, &y);

        if(o == 1)
            uneste(grupa(x),grupa(y));
        else
        {
            int g1 = grupa(x), g2 = grupa(y);

            printf("%s\n", g1 == g2 ? "DA" : "NU");
        }
    }

    return 0;
}