Cod sursa(job #1699628)

Utilizator cosmin79Carabet Cosmin Andrei cosmin79 Data 7 mai 2016 23:30:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <cstdio>
const int NMAX = 100505;
 
int N, M, par[NMAX], rnk[NMAX];
 
void init() {
    for (int i = 1; i <= N; i++) {
        par[i] = i;
    }
}
 
int findRoot(int node) {
    int root = node, aux;
    while (par[root] != root) {
        root = par[root];
    }
    while (node != root) {
        aux = par[node];
        par[node] = root;
        node = aux;
    }
 
    return root;
}
 
void unite(int x, int y) {
    if (rnk[x] < rnk[y]) {
        par[x] = y;
    } else {
        par[y] = x;
        if (rnk[x] == rnk[y]) {
            rnk[x]++;
        }
    }
}
 
int main() {
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
 
    scanf("%d%d", &N, &M);
    init();
    int type, x, y;
    for (int i = 1; i <= M; i++) {
        scanf("%d%d%d", &type, &x, &y);
        if (type == 1) {
            unite(findRoot(x), findRoot(y));
        } else {
            if (findRoot(x) == findRoot(y)) {
                printf("DA\n");
            } else {
                printf("NU\n");
            }
        }
    }
    return 0;
}