Cod sursa(job #780806)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 21 august 2012 21:36:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <cstdio>

using namespace std;

const int kMaxN = 100005;

int N, F[kMaxN];

inline int Find(int X) {
    int Root = X;
    for (; F[Root]; Root = F[Root]);
    for (int Y; X != Root; Y = F[X], F[X] = Root, X = Y);
    return Root;
}

inline void Merge(int X, int Y) {
    X = Find(X), Y = Find(Y);
    if (X != Y)
        F[X] = Y;
}

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