Cod sursa(job #884411)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 20 februarie 2013 21:47:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.95 kb
#include <cstdio>
#include <iostream>

using namespace std;

#define Nmax 100001

int tata[Nmax];
int rang[Nmax];

int N, M, a, b, c;

int gaseste(int x){

    int R, y;

    for( R = x; R != tata[R]; R = tata[R] );

    for( ; tata[x] != x; ){

        y = tata[x];
        tata[x] = R;
        x = y;
    }

    return R;
}

void reuneste(int x, int y){

    if(rang[x] > rang[y])
        tata[y] = x;
    else
        tata[x] = y;

    if(rang[x] == rang[y])
        rang[x]++;
}

int main(){

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

    scanf("%d %d", &N, &M);

    for(int i = 1; i <= N; i++)
        tata[i] = i,
        rang[i] = 1;

    for(; M; M--){

        scanf("%d %d %d", &c, &a, &b);

        if(c == 2)
            if(gaseste(a) == gaseste(b))
                printf("DA\n");
            else
                printf("NU\n");
        else
            reuneste(gaseste(a), gaseste(b));
    }

    return 0;
}