Cod sursa(job #1163135)

Utilizator cbanu96Banu Cristian cbanu96 Data 1 aprilie 2014 10:34:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <cstdio>

using namespace std;

#define FILEIN "disjoint.in"
#define FILEOUT "disjoint.out"
#define NMAX 100005

int Set[NMAX], Rank[NMAX], N, M;

int Find(int);
void Union(int, int);

void Union(int x, int y) {
    int xRoot = Find(x),
        yRoot = Find(y);

    if (xRoot == yRoot)
        return;

    if (Rank[xRoot] < Rank[yRoot]) {
        Set[xRoot] = yRoot;
        return;
    }
    if (Rank[xRoot] > Rank[yRoot]) {
        Set[yRoot] = xRoot;
        return;
    }

    Set[yRoot] = xRoot;
    Rank[yRoot] = Rank[xRoot] + 1;
}

int Find(int x) {
    if (Set[x] == x)
        return x;

    return (Set[x] = Find(Set[x]));
}

int main() {
    freopen(FILEIN, "r", stdin);
    freopen(FILEOUT, "w", stdout);

    for (scanf("%d", &N); N; N--) {
        Set[N] = N;
    }

    for (scanf("%d", &M); M; M--) {
        int T, x, y;

        scanf("%d %d %d", &T, &x, &y);

        if (T == 1) {
            Union(x, y);
        } else {
            if (Find(x) == Find(y)) {
                printf("DA\n");
            } else {
                printf("NU\n");
            }
        }
    }

    return 0;
}