Cod sursa(job #1804936)

Utilizator andreiskiorAndrei Cristian Nastase andreiskior Data 13 noiembrie 2016 12:05:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <stdio.h>

int depth[100001];
int boss[100001];

int find(int u)
{
    if(u == boss[u])
        return u;
    return boss[u] = find(boss[u]);
}

void unify(int u1, int u2)
{
    int x = find(u1);
    int y = find(u2);
    if(x != y)
    {
        if(depth[x] > depth[y])
        {
            boss[x] = boss[y];
            depth[y] += depth[x];
        }
        else
        {
            boss[y] = boss[x];
            depth[x] += depth[y];
        }
    }
}

int main()
{
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    int n,m,i,type,i1,i2;
    scanf("%d%d",&n,&m);
    for(i = 1; i <= 100000; ++i)
    {
        depth[i] = 1;
        boss[i] = i;
    }
    for(i = 1; i <= m; ++i)
    {
        scanf("%d%d%d",&type,&i1,&i2);
        if(type == 1)
            unify(i1,i2);
        else
        {
            if( find(i1) == find(i2) )
                printf("DA\n");
            else
                printf("NU\n");
        }
    }
    return 0;
}