Cod sursa(job #1039196)

Utilizator stefan.friptuPetru Stefan Friptu stefan.friptu Data 22 noiembrie 2013 17:45:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <cstdio>

using namespace std;

long h[100001],t[100001],n,m,i,tip,mbr1,mbr2;

long Find (long x)
{
    while(t[x]!=x)
        x=t[x];
    return x;
}

void Union(long x,long y)
{
    if(h[x]==h[y])
    {
        h[x]++;
        t[y]=x;
    }
    else
        if(h[x]>h[y])
            t[y]=x;
        else
            t[x]=y;
}

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

    scanf("%ld%ld",&n,&m);

    for(i=1;i<=n;i++)
        t[i]=i;

    for(i=1;i<=m;i++)
    {
        scanf("%ld%ld%ld",&tip,&mbr1,&mbr2);

        long cm1,cm2;

        cm1=Find(mbr1);
        cm2=Find(mbr2);

        if(tip==2)
        {
            if(cm1==cm2)
                printf("DA\n");
            else
                printf("NU\n");
        }
        else
            Union(cm1,cm2);
    }

    return 0;
}