Cod sursa(job #1024254)

Utilizator eugen_ptrEugen Patru eugen_ptr Data 8 noiembrie 2013 14:52:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <cstdio>
using namespace std;

int n,m,tata[100005],h[100005];
int tip,x,y;

int cauta(int x)
{
    int rx=x;
    while ( tata[rx] != rx)
    {
        rx=tata[rx];
    }
    int y=x;
    while ( tata[y] != y)
    {
        int aux=tata[y];
        tata[y]=rx;
        y=aux;
    }
    return rx;
}

void reunion(int x, int y)
{
    int rx=cauta(x);
    int ry=cauta(y);
    if (ry != rx)
    {
        if (h[rx] < h[ry])
            tata[rx]=ry;
        else
        {
            tata[ry]=rx;
            if (h[rx] == h[ry])
                h[rx]++;
        }
    }

}

void rezolvare()
{
    scanf("%d %d",&n,&m);
    for (int i=1; i<=n; i++)
    {
        tata[i]=i;
        h[i]=0;
    }

    for (int i=1; i<=m; i++)
    {
        scanf("%d%d%d",&tip,&x,&y);
        if ( tip == 1)
            reunion(x,y);
        else
        {
            if (cauta(x) == cauta(y))
                printf("DA\n");
            else printf("NU\n");
        }
    }

}

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