Cod sursa(job #2238286)

Utilizator maria_neagoieMaria Neagoie maria_neagoie Data 5 septembrie 2018 10:09:11
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <cstdio>
using namespace std;
const int NMAX=100000;
int t[NMAX+5],h[NMAX+5];
int findset(int x)
{
    while(x!=t[x])
        x=t[x];
    return x;
}
void unionset(int x,int 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);
    int n,m,i,tx,ty,p,x,y;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        t[i]=i;
        h[i]=1;
    }
    for(i=1;i<=m;i++)
    {
        scanf("%d%d%d",&p,&x,&y);
        if(p==1)
        {
            tx=findset(x);
            ty=findset(y);
            if(tx!=ty)
                unionset(tx,ty);
        }
        else
        {
            if(findset(x)==findset(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
    }
    return 0;
}