Cod sursa(job #974876)

Utilizator gbi250Gabriela Moldovan gbi250 Data 18 iulie 2013 16:46:09
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <cstdio>
#define vert 100002
using namespace std;
int n, m, cod, x, y, i, h[vert], father[vert];

void UNION(int x, int y)
{
    if(h[x]>h[y])
        father[y]=x;
    else
    {
        father[x]=y;
        if(h[x]==h[y])
            h[y]++;
    }
}

int root(int x)
{
    int r=x;
    while(father[r])
        r=father[r];
    int f, y=x;
    while(y!=r)
    {
        f=father[y];
        father[y]=r;
        y=f;
    }
    return r;
}


int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    scanf("%d %d", &n, &m);
    for(i=1;i<=n;++i)
        father[i]=0;
    for(i=1;i<=m;++i)
    {
        scanf("%d %d %d", &cod, &x, &y);
        if(cod==1)
            UNION(x, y);
        else if(root(x)==root(y))
            printf("DA\n");
        else
            printf("NU\n");
    }
    return 0;
}