Cod sursa(job #1119206)

Utilizator visanrVisan Radu visanr Data 24 februarie 2014 16:11:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <cstdio>
using namespace std;

const int NMAX = 100010;

int N, M, Father[NMAX], Size[NMAX], X, Y, Type;

int Find(int X)
{
    int Y, P;
    for(P = X; P != Father[P]; P = Father[P]);
    for(; X != P; )
    {
        Y = Father[X];
        Father[X] = P;
        X = Y;
    }
    return P;
}

void Merge(int X, int Y)
{
    if(X == Y) return ;
    if(Size[X] >= Size[Y]) Size[X] += Size[Y], Father[Y] = X;
    else Size[Y] += Size[X], Father[X] = Y;
}

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

    scanf("%i %i", &N, &M);
    for(int i = 1; i <= N; ++ i) Father[i] = i, Size[i] = 1;

    for(; M; M --)
    {
        scanf("%i %i %i", &Type, &X, &Y);
        int RootX = Find(X), RootY = Find(Y);
        if(Type == 1) Merge(RootX, RootY);
        else
        {
            if(RootX == RootY) printf("DA\n");
            else printf("NU\n");
        }
    }
}