Cod sursa(job #1024227)

Utilizator ucnahHancu Andrei ucnah Data 8 noiembrie 2013 14:16:29
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <cstdio>

using namespace std;
int n,m,tata[100010],cod,x,y,h[100005];
void reuniune(int x,int y)
{
    if (h[x]<h[y])
        tata[x]=y;
    else if(h[x]>h[y])
        tata[y]=x;
    else
    {
        tata[x]=y;
        h[y]++;
    }
}
int cauta(int x)
{
    while(x!=tata[x])
        x=tata[x];
    return x;
}
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]=i;
    }
    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;
}