Cod sursa(job #800855)

Utilizator SchumiDumitru Andrei Georgian Schumi Data 22 octombrie 2012 20:19:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;

const int N = 100005;

int n, q;
int father[N];

int get_root(int node) {
    if (father[node] == node)
        return node;

    father[node] = get_root(father[node]);

    return father[node];
}

void unite(int x, int y) {
    int root_x = get_root(x);
    int root_y = get_root(y);

    if (root_x == root_y)
        return;

    if (rand() & 1)
        father[root_x] = root_y;
    else
        father[root_y] = root_x;
}

void init() {
    for (int i = 1; i <= n; ++i)
        father[i] = i;
}

int main() {
    srand(time(NULL));
    assert(freopen("disjoint.in", "r", stdin) != NULL);
    assert(freopen("disjoint.out", "w", stdout) != NULL);

    assert(scanf("%d %d", &n, &q) == 2);
    init();
    while (q--) {
        int type, x, y;
        assert(scanf("%d %d %d", &type, &x, &y) == 3);
        if (type == 2) {
            if (get_root(x) == get_root(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
        else
            unite(x, y);
    }
}