Cod sursa(job #1324620)

Utilizator gabrielvGabriel Vanca gabrielv Data 22 ianuarie 2015 16:20:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <cstdio>

using namespace std;

#define NMAX 100010

int Father[NMAX];
int MaxDepth[NMAX];

int Root(int n)
{
    if(n == Father[n])
        return n;

    Father[n] = Root(Father[n]);
    return Father[n];
}

void Join(int a, int b)
{
    int rootA = Root(a);
    int rootB = Root(b);

    if(MaxDepth[rootA] > MaxDepth[rootB])
        Father[rootB] = rootA;
    else
        Father[rootA] = rootB;

    if(MaxDepth[rootA] == MaxDepth[rootB])
        MaxDepth[rootB]++;
}

inline bool AreBrothers(int a, int b)
{
    return Root(a)==Root(b);
}

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

    int N,M,x,y,op;
    scanf("%d%d",&N,&M);

    for(int i=1;i<=N;i++)
        Father[i] = i;

    while(M--)
    {
        scanf("%d%d%d",&op,&x,&y);
        if(op==1)
            Join(x,y);
        else
            if(AreBrothers(x,y))
                printf("DA\n");
            else
                printf("NU\n");
    }
    return 0;
}