Cod sursa(job #1806372)

Utilizator UrsuDanUrsu Dan UrsuDan Data 15 noiembrie 2016 11:11:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>

using namespace std;

int tata[100010];
int h[100010];

int caut(int x)
{
    if(x==tata[x])
        return x;
    else
    {
        tata[x]=caut(tata[x]);
        return tata[x];
    }
}

void unesc (int x,int y)
{
    int a,b;
    a=caut(x);
    b=caut(y);
    if(h[a]>h[b])
        tata[a]=b;
    else
    {
        tata[b]=a;
        h[b]++;
    }
}

int main()
{
    freopen ("disjoint.in","r",stdin);
    freopen ("disjoint.out","w",stdout);
    srand(time(0));
    int n,m,x,y,p,i;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
        tata[i]=i;
        h[i]=1;
    }
    for(i=1;i<=m;i++)
    {
        scanf("%d%d%d",&p,&x,&y);
        if(p==1)
            unesc(x,y);
        else if(caut(x)==caut(y))
            printf("DA\n");
        else
            printf("NU\n");
    }
    return 0;
}