Cod sursa(job #884311)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 20 februarie 2013 20:53:50
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <cstdio>
#include <cassert>

using namespace std;

const int MAX_N = 100005;

int N, Father[MAX_N];

int Find(int X) {
    if (X == Father[X])
        return X;
    return (Father[X] = Find(Father[X]));
}

bool Merge(int X, int Y) {
    X = Find(X); Y = Find(Y);
    if (X != Y)
        Father[Y] = X;
}

void Initialize() {
    for (int X = 1; X <= N; ++X)
        Father[X] = X;
}

int main() {
    assert(freopen("disjoint.in", "r", stdin));
    assert(freopen("disjoint.out", "w", stdout));
    int M; assert(scanf("%d %d", &N, &M) == 2);
    Initialize();
    for (; M > 0; --M) {
        int Type, X, Y; assert(scanf("%d %d %d", &Type, &X, &Y) == 3);
        if (Type == 1)
            assert(Merge(X, Y));
        else
            printf("%s\n", (Find(X) == Find(Y) ? "DA" : "NU"));
    }
    return 0;
}