Cod sursa(job #1007287)

Utilizator FlameingoAiordachioaei Marius Flameingo Data 8 octombrie 2013 18:20:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <cstdio>
using namespace std;

const int NMAX = 100003;

int father[NMAX], depth_max[NMAX];

inline int set_root (int node) {

    int root, x;
    for (root = node; father[root] != root; root = father[root]);
    for (; father[node] != node; node = x)
        x = father[node],
        father[node] = root;
    return root;

}

inline void set_unite_roots (int root, int _root) {

    if (depth_max[root] < depth_max[_root])
        father[root] = _root;
    else
        if (depth_max[_root] < depth_max[root])
            father[_root] = root;
        else
            father[root] = _root,
            ++depth_max[_root];

}

int main () {

    freopen ("disjoint.in", "r", stdin);
    freopen ("disjoint.out", "w", stdout);
    int N, M, cod, i, j;
    scanf ("%d%d", &N, &M);
    for (i = 1; i <= N; ++i)
        father[i] = i;
    while (M--) {
        scanf ("%d%d%d", &cod, &i, &j);
        if (cod == 1)
            set_unite_roots (set_root (i), set_root (j));
        else
            if (set_root (i) == set_root (j))
                printf ("DA\n");
            else
                printf ("NU\n");
    }

}