Cod sursa(job #1024240)

Utilizator ucnahHancu Andrei ucnah Data 8 noiembrie 2013 14:33:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <cstdio>

using namespace std;
int n,m,tata[100010],cod,x,y,h[100005];
int cauta(int x)
{
    int rx=x;
    while(rx!=tata[rx])
        rx=tata[rx];
    int y=x;
    while(y!=tata[y])
    {
        int aux=tata[y];
        tata[y]=rx;
        y=aux;
    }
    return rx;
}
void reuniune(int x,int y)
{
    int rx=cauta(x);
    int ry=cauta(y);
    if(rx!=ry)
    {
        if(h[rx]<h[ry])
            tata[rx]=ry;
        else{
            tata[ry]=rx;
            if(h[rx]==h[ry])
                    h[rx]++;
        }
    }
}
int main()
{
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    scanf("%d %d",&n,&m);
    for (int i=1;i<=n;i++)
    {
        tata[i]=i;
        h[i]=1;
    }
    for(int i=0;i<m;i++)
    {
        scanf("%d %d %d",&cod,&x,&y);
        if(cod==1)
        {
            reuniune(x,y);
        }
        else
        {
            if(cauta(x)==cauta(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
    }


    return 0;
}